Pages Reference

Module Summary

next.pages exposes the page module API, the @context decorator, and the layout composition helpers.

Public API

class next.pages.Page[source]

Coordinate template loading, context, layouts, rendering, and URL wiring.

__init__() None[source]

Initialise fresh registries and layout manager.

File-based template loaders are not held as an instance attribute. The module-level build_registered_loaders() helper caches them and invalidates on settings_reloaded.

register_template(file_path: Path, template_str: str) None[source]

Store rendered template source for file_path.

context(func_or_key: Callable[..., Any] | str | None = None, *, inherit_context: bool = False, serialize: bool = False, serializer: JsContextSerializer | None = None) Callable[[Callable[..., Any]], Callable[..., Any]][source]

Register a keyed or dict-merge @context for the caller file.

Pass serialize=True to include the return value in Next.context so JavaScript code on the page can read it via window.Next.context. Pass serializer= to route this key through a custom JsContextSerializer instead of the global JS_CONTEXT_SERIALIZER setting.

build_render_context(file_path: Path, *args: object, **kwargs: object) dict[str, object][source]

Build the full render context dict used by render.

The returned dict includes _next_js_context holding the subset of values marked serialize=True. render pops that key and seeds the StaticCollector with it before creating the Django template context.

render_with_static_assets(file_path: Path, template_str: str, context_data: dict[str, object], *, request: HttpRequest | None = None) tuple[str, StaticCollector][source]

Render template_str and inject collected static assets.

The method seeds a fresh StaticCollector, hydrates it with the JS context that build_render_context left under the _next_js_context key, discovers co-located assets for the page, renders the Django template, and replaces placeholders through default_manager.inject. The active request reaches the static backend so request-aware subclasses can rewrite URLs. Both the rendered HTML and the collector are returned so callers can reuse the collector for telemetry without a second rendering pass. Suitable for the canonical page render path and for partial paths such as form-error rerenders.

render(file_path: Path, *args: object, **kwargs: object) str[source]

Render the page with Django Template and the static collector.

The static body source is the template attribute or any registered file-based TemplateLoader. The result is composed through the ancestor layout chain and cached in _template_registry. Direct callers of Page.render do not invoke render(). The unified view handles that path so dynamic bodies skip the registry cache.

has_template(file_path: Path, module: types.ModuleType | None = None) bool[source]

Return whether any source can supply a template for this path.

create_url_pattern(url_path: str, file_path: Path, url_parser: URLPatternParser) URLPattern | None[source]

Return a path() pattern for a page, template, or virtual entry.

class next.pages.Context(source: object | None = None, *, default: object = <object object>)[source]

Mark a parameter default so the value is taken from context_data.

An empty Context() reads the parameter name from context_data. A string source reads that context key. A callable source is called with DI-resolved arguments. Any other object becomes a constant. The default keyword supplies a fallback when the context key is missing.

source: object | None
default: object
__init__(source: object | None = None, *, default: object = <object object>) None
class next.pages.ContextResult(context_data: dict[str, Any], js_context: dict[str, Any], js_context_serializers: dict[str, JsContextSerializer] = <factory>)[source]

Hold the full template context and its JavaScript-serializable subset.

context_data contains every value merged into the Django template context. js_context contains only the subset marked serialize=True, which the renderer later hands to StaticCollector.add_js_context. js_context_serializers carries per-key serializer overrides supplied through @context(serializer=…) so the collector can route a single key through a custom serializer without affecting other keys.

context_data: dict[str, Any]
js_context: dict[str, Any]
js_context_serializers: dict[str, JsContextSerializer]
__init__(context_data: dict[str, Any], js_context: dict[str, Any], js_context_serializers: dict[str, JsContextSerializer] = <factory>) None
next.pages.context(func_or_key: Callable[..., Any] | str | None = None, *, inherit_context: bool = False, serialize: bool = False, serializer: JsContextSerializer | None = None) Callable[[Callable[..., Any]], Callable[..., Any]]

Register a keyed or dict-merge @context for the caller file.

Pass serialize=True to include the return value in Next.context so JavaScript code on the page can read it via window.Next.context. Pass serializer= to route this key through a custom JsContextSerializer instead of the global JS_CONTEXT_SERIALIZER setting.

Note

The serialize and serializer keyword arguments opt a value into the JS context. See the topic guide for details.

next.pages.page = <next.pages.manager.Page object>

Coordinate template loading, context, layouts, rendering, and URL wiring.

Manager

Page manager and its process-wide singleton.

Page orchestrates template loading, context collection, layout composition, rendering, and URL-pattern wiring. page is the application-wide singleton. context is a convenience alias for page.context used by the @context decorator in user code.

class next.pages.manager.Page[source]

Coordinate template loading, context, layouts, rendering, and URL wiring.

__init__() None[source]

Initialise fresh registries and layout manager.

File-based template loaders are not held as an instance attribute. The module-level build_registered_loaders() helper caches them and invalidates on settings_reloaded.

register_template(file_path: Path, template_str: str) None[source]

Store rendered template source for file_path.

build_render_context(file_path: Path, *args: object, **kwargs: object) dict[str, object][source]

Build the full render context dict used by render.

The returned dict includes _next_js_context holding the subset of values marked serialize=True. render pops that key and seeds the StaticCollector with it before creating the Django template context.

render_with_static_assets(file_path: Path, template_str: str, context_data: dict[str, object], *, request: HttpRequest | None = None) tuple[str, StaticCollector][source]

Render template_str and inject collected static assets.

The method seeds a fresh StaticCollector, hydrates it with the JS context that build_render_context left under the _next_js_context key, discovers co-located assets for the page, renders the Django template, and replaces placeholders through default_manager.inject. The active request reaches the static backend so request-aware subclasses can rewrite URLs. Both the rendered HTML and the collector are returned so callers can reuse the collector for telemetry without a second rendering pass. Suitable for the canonical page render path and for partial paths such as form-error rerenders.

render(file_path: Path, *args: object, **kwargs: object) str[source]

Render the page with Django Template and the static collector.

The static body source is the template attribute or any registered file-based TemplateLoader. The result is composed through the ancestor layout chain and cached in _template_registry. Direct callers of Page.render do not invoke render(). The unified view handles that path so dynamic bodies skip the registry cache.

has_template(file_path: Path, module: types.ModuleType | None = None) bool[source]

Return whether any source can supply a template for this path.

create_url_pattern(url_path: str, file_path: Path, url_parser: URLPatternParser) URLPattern | None[source]

Return a path() pattern for a page, template, or virtual entry.

Registry

Per-page.py context-callable registry and layout watch helpers.

PageContextRegistry stores the list of context functions bound to each page.py path, and merges their return values (with keyed and dict-merge semantics) at render time. The watch helpers list template.djx and layout.djx files under page roots for the autoreloader and for the static finder.

class next.pages.registry.PageContextEntry(func: Callable[..., Any], inherit_context: bool, serialize: bool, serializer: JsContextSerializer | None = None)[source]

One context callable registered for a page.py file.

The optional serializer overrides the global JS context serializer for the value this callable produces, but only when serialize is true. Backed by NamedTuple so the hot register_context path allocates a plain tuple rather than a frozen dataclass instance.

func: Callable[..., Any]

Alias for field number 0

inherit_context: bool

Alias for field number 1

serialize: bool

Alias for field number 2

serializer: JsContextSerializer | None

Alias for field number 3

next.pages.registry.get_layout_djx_paths_for_watch() set[Path][source]

Return every layout.djx path under page trees.

next.pages.registry.get_template_djx_paths_for_watch() set[Path][source]

Return every template.djx path under page trees.

class next.pages.registry.PageContextRegistry(resolver: DependencyResolver | None = None)[source]

Register per-page.py context callables and merge their output.

__init__(resolver: DependencyResolver | None = None) None[source]

Initialise with an optional resolver and an empty registry.

register_context(file_path: Path, key: str | None, func: Callable[..., Any], *, inherit_context: bool = False, serialize: bool = False, serializer: JsContextSerializer | None = None) None[source]

Bind func to file_path with keyed or dict-merge semantics.

collect_context(file_path: Path, *args: object, **kwargs: object) ContextResult[source]

Merge inherited ancestor page.py context with this file’s context callables.

Inherited context comes from @context(..., inherit_context=True) callables in ancestor page.py files, not from layout files. The returned ContextResult separates the full template context from the JavaScript-serializable subset. The js_context uses first-registration semantics so that page-level values always take priority over inherited ones.

Loaders

TemplateLoader is the abstract contract for sourcing template text from a page.py path.

class next.pages.loaders.TemplateLoader[source]

Pluggable source of template text for a page.py path.

Subclasses set source_name to the filename they back. Typical values are “template.djx” or “template.md”. The name is surfaced in the next.W043 body-source conflict check.

source_name: ClassVar[str] = ''
abstractmethod can_load(file_path: Path) bool[source]

Return whether this loader applies without heavy work.

abstractmethod load_template(file_path: Path) str | None[source]

Return the template source. Return None when unavailable.

source_path(file_path: Path) Path | None[source]

Return the filesystem path this loader reads for file_path.

The page manager uses the result to snapshot file mtimes for stale-cache detection. The default returns None for non-file-based loaders. Subclasses override when they back a sibling file.

DjxTemplateLoader reads a sibling template.djx next to page.py. It is the only loader in the default TEMPLATE_LOADERS chain.

class next.pages.loaders.DjxTemplateLoader[source]

Load from a sibling template.djx next to page.py.

source_name: ClassVar[str] = 'template.djx'
can_load(file_path: Path) bool[source]

Return whether sibling template.djx exists.

load_template(file_path: Path) str | None[source]

Return the file contents of template.djx.

source_path(file_path: Path) Path | None[source]

Return the sibling template.djx path for stale-cache detection.

PythonTemplateLoader reads a template attribute defined inside page.py. It is not registered by default. Add its dotted path to NEXT_FRAMEWORK["TEMPLATE_LOADERS"] to enable it. The manager already consults module.template directly, so registering this loader changes nothing at render time and only affects how the next.W043 conflict check reports the source.

class next.pages.loaders.PythonTemplateLoader[source]

Load from page.py when the module defines a template attribute.

source_name: ClassVar[str] = 'template'
can_load(file_path: Path) bool[source]

Return whether the module loads and defines template.

load_template(file_path: Path) str | None[source]

Return module.template if the module exposes it.

LayoutTemplateLoader composes nested layout.djx wrappers around the page template, walking the directory chain from the page up to the page root. It runs on a dedicated path and is not registered through TEMPLATE_LOADERS.

class next.pages.loaders.LayoutTemplateLoader[source]

Compose nested layout.djx wrappers around the page template.

can_load(file_path: Path) bool[source]

Return whether at least one layout.djx exists on the path.

load_template(file_path: Path) str | None[source]

Return the composed template with the page inside the innermost slot.

compose_body(body: str, file_path: Path) str[source]

Wrap body through the ancestor layout chain for file_path.

Returns body verbatim when no layouts apply. When a sibling layout.djx exists the innermost layout owns the {% block template %} slot, so body is substituted as-is. Otherwise body is wrapped in a {% block template %} block before substitution so the ancestor layout’s placeholder remains a valid block.

LayoutManager caches the composed layout string per page path so repeated renders skip recomposition.

class next.pages.loaders.LayoutManager[source]

Cache composed layout strings per page path.

__init__() None[source]

Initialise an empty layout cache.

discover_layouts_for_template(template_path: Path) str | None[source]

Compose and store layout text when LayoutTemplateLoader applies.

get_layout_template(template_path: Path) str | None[source]

Return the cached composed template for template_path.

clear_registry() None[source]

Drop all cached layout strings.

Processors

Context-processor discovery and loading.

Context processors come from two sources. First, each entry in NEXT_FRAMEWORK[“DEFAULT_PAGE_BACKENDS”] may list processors under OPTIONS.context_processors. Second, Django’s TEMPLATES setting includes its own OPTIONS.context_processors. Both sources merge with Next-router entries taking precedence and duplicates dropped.

System Checks

next.pages.checks registers the Django system checks for the pages subsystem. They run through uv run python manage.py check.

The module exports seven check callables.

  • check_context_functions.

  • check_context_processor_signature.

  • check_layout_templates.

  • check_page_functions.

  • check_pages_structure.

  • check_request_in_context.

  • check_template_loaders.

See System Checks for each check identifier, its condition, and the full autodoc of next.pages.checks.

Signals

See Signals Reference and Signals for the pages signals (template_loaded, context_registered, page_rendered).

See Also

See also

Pages for the topic guide. Page Discovery for the internal pipeline.