Classes
Template
21
▼
Compiled template ready for rendering.
Wraps a compiled code object containing a ``render(ctx, _bl…
Template
21
▼
Compiled template ready for rendering.
Wraps a compiled code object containing arender(ctx, _blocks)function.
Templates are immutable and thread-safe for concurrentrender()calls.
Thread-Safety:
- Template object is immutable after construction
- Each
render()call creates local state only (buf list) - Multiple threads can render the same template simultaneously
Memory Safety:
Usesweakref.ref(env)to prevent circular reference leaks:
Template → (weak) → Environment → _cache → Template
Methods: render(**context): Render template with given variables render_async(**context): Async render for templates with await
Error Enhancement:
Runtime errors are caught and enhanced with template context:
```
TemplateRuntimeError: 'NoneType' has no attribute 'title'
Location: article.html:15
Expression: {{ post.title }}
Values:
post = None (NoneType)
Suggestion: Check if 'post' is defined before accessing .title
```
Attributes
| Name | Type | Description |
|---|---|---|
name |
— |
Template identifier (for error messages) |
filename |
— |
Source file path (for error messages) |
Methods
name
0
str | None
▼
Template name.
property
name
0
str | None
▼
def name(self) -> str | None
Returns
str | None
filename
0
str | None
▼
Source filename.
property
filename
0
str | None
▼
def filename(self) -> str | None
Returns
str | None
is_async
0
bool
▼
True if this template uses async constructs (async for / await).
Part of RFC: …
property
is_async
0
bool
▼
def is_async(self) -> bool
True if this template uses async constructs (async for / await).
Part of RFC: rfc-async-rendering.
Returns
bool
render
2
str
▼
Render template with given context.
User context is now CLEAN - no internal ke…
render
2
str
▼
def render(self, *args: Any, **kwargs: Any) -> str
Render template with given context.
User context is now CLEAN - no internal keys injected. Internal state (_template, _line, _include_depth, _cached_blocks, _cached_stats) is managed via RenderContext ContextVar.
Parameters
| Name | Type | Description |
|---|---|---|
*args |
— |
|
**kwargs |
— |
Returns
str
Rendered template as string
render_block
3
str
▼
Render a single block from the template.
Renders just the named block, useful …
render_block
3
str
▼
def render_block(self, block_name: str, *args: Any, **kwargs: Any) -> str
Render a single block from the template.
Renders just the named block, useful for caching blocks that only depend on site-wide context (e.g., navigation, footer).
Parameters
| Name | Type | Description |
|---|---|---|
block_name |
— |
Name of the block to render (e.g., "nav", "footer") *args: Single dict of context variables **kwargs: Context variables as keyword arguments |
*args |
— |
|
**kwargs |
— |
Returns
str
Rendered block HTML as string
render_with_blocks
3
str
▼
Render this template with pre-rendered HTML injected into blocks.
Enables prog…
render_with_blocks
3
str
▼
def render_with_blocks(self, block_overrides: dict[str, str], *args: Any, **kwargs: Any) -> str
Render this template with pre-rendered HTML injected into blocks.
Enables programmatic layout composition: render a page's content,
then inject it as thecontentblock of a parent layout template,
without needing{% extends %}in the template source.
Each key in block_overrides names a block; the value is a pre-rendered HTML string that replaces that block's default content.
Parameters
| Name | Type | Description |
|---|---|---|
block_overrides |
— |
Mapping of block name → pre-rendered HTML string. *args: Single dict of context variables. **kwargs: Context variables as keyword arguments. |
*args |
— |
|
**kwargs |
— |
Returns
str
Rendered template as string with block overrides applied.
render_stream
2
▼
Render template as a generator of HTML chunks.
Yields chunks at every statemen…
render_stream
2
▼
def render_stream(self, *args: Any, **kwargs: Any)
Render template as a generator of HTML chunks.
Yields chunks at every statement boundary, enabling progressive delivery via chunked transfer encoding.
Parameters
| Name | Type | Description |
|---|---|---|
*args |
— |
|
**kwargs |
— |
list_blocks
0
list[str]
▼
List all blocks defined in this template.
list_blocks
0
list[str]
▼
def list_blocks(self) -> list[str]
Returns
list[str]
List of block names available for render_block()
render_async
2
str
▼
Async wrapper for synchronous render.
Runs the synchronous ``render()`` method…
async
render_async
2
str
▼
async def render_async(self, *args: Any, **kwargs: Any) -> str
Async wrapper for synchronous render.
Runs the synchronousrender()method in a thread pool to avoid
blocking the event loop.
Parameters
| Name | Type | Description |
|---|---|---|
*args |
— |
|
**kwargs |
— |
Returns
str
render_stream_async
2
▼
Render template as an async generator of HTML chunks.
For templates with async…
async
render_stream_async
2
▼
async def render_stream_async(self, *args: Any, **kwargs: Any)
Render template as an async generator of HTML chunks.
For templates with async constructs ({% async for %}, {{ await }}), this calls the native async render function. For sync templates, it wraps the sync render_stream() in an async generator.
Parameters
| Name | Type | Description |
|---|---|---|
*args |
— |
|
**kwargs |
— |
render_block_stream_async
3
▼
Render a single block as an async stream.
Looks up the async streaming block f…
async
render_block_stream_async
3
▼
async def render_block_stream_async(self, block_name: str, *args: Any, **kwargs: Any)
Render a single block as an async stream.
Looks up the async streaming block function first, falls back to the sync streaming block function wrapped in an async generator.
Parameters
| Name | Type | Description |
|---|---|---|
block_name |
— |
Name of the block to render *args: Single dict of context variables **kwargs: Context variables as keyword arguments |
*args |
— |
|
**kwargs |
— |
Internal Methods 8 ▼
_env
0
Environment
▼
Get the Environment (dereferences weak reference).
property
_env
0
Environment
▼
def _env(self) -> Environment
Returns
Environment
__init__
6
▼
Initialize template with compiled code.
__init__
6
▼
def __init__(self, env: Environment, code: types.CodeType, name: str | None, filename: str | None, optimized_ast: TemplateNode | None = None, source: str | None = None)
Parameters
| Name | Type | Description |
|---|---|---|
env |
— |
Parent Environment (stored as weak reference) |
code |
— |
Compiled Python code object |
name |
— |
Template name (for error messages) |
filename |
— |
Source filename (for error messages) |
optimized_ast |
— |
Optional preserved AST for introspection. If None, introspection methods return empty results. Default:None
|
source |
— |
Template source for runtime error snippets. Stored for use by _enhance_error() to provide source context in TemplateRuntimeError exceptions. Default:None
|
_build_context
3
dict[str, Any]
▼
Build render context from args and kwargs.
Shared by render, render_block, ren…
_build_context
3
dict[str, Any]
▼
def _build_context(self, args: tuple[Any, ...], kwargs: dict[str, Any], method_name: str) -> dict[str, Any]
Build render context from args and kwargs.
Shared by render, render_block, render_with_blocks, render_stream, render_stream_async, render_block_stream_async.
Parameters
| Name | Type | Description |
|---|---|---|
args |
— |
|
kwargs |
— |
|
method_name |
— |
Returns
dict[str, Any]
_enhance_error
2
Exception
▼
Enhance a generic exception with template context from RenderContext.
Converts…
_enhance_error
2
Exception
▼
def _enhance_error(self, error: Exception, render_ctx: RenderContext) -> Exception
Enhance a generic exception with template context from RenderContext.
Converts generic Python exceptions into TemplateRuntimeError with template name, line number, and source snippet context.
Parameters
| Name | Type | Description |
|---|---|---|
error |
— |
|
render_ctx |
— |
Returns
Exception
_escape
1
str
▼
HTML-escape a value.
Uses optimized html_escape from utils.html module.
Comple…
staticmethod
_escape
1
str
▼
def _escape(value: Any) -> str
HTML-escape a value.
Uses optimized html_escape from utils.html module. Complexity: O(n) single-pass using str.translate().
Parameters
| Name | Type | Description |
|---|---|---|
value |
— |
Returns
str
_safe_getattr
2
Any
▼
Get attribute with dict fallback and None-safe handling.
Resolution order:
- D…
staticmethod
_safe_getattr
2
Any
▼
def _safe_getattr(obj: Any, name: str) -> Any
Get attribute with dict fallback and None-safe handling.
Resolution order:
- Dicts: subscript first (user data), getattr fallback (methods).
This prevents dict method names like
items,keys,values,getfrom shadowing user data keys. - Objects: getattr first, subscript fallback.
None Handling (like Hugo/Go templates):
- If obj is None, returns UNDEFINED (prevents crashes)
- If attribute value is None, returns "" (normalizes output)
Not-Found Handling:
- Returns the
UNDEFINEDsentinel when the attribute/key is not found.UNDEFINEDstringifies as""(so template output is unchanged) butis_defined()recognises it as not defined, fixingx.missing is defined→ False.
Complexity: O(1)
Parameters
| Name | Type | Description |
|---|---|---|
obj |
— |
|
name |
— |
Returns
Any
_getattr_preserve_none
2
Any
▼
Get attribute with dict fallback, preserving None values.
Like _safe_getattr b…
staticmethod
_getattr_preserve_none
2
Any
▼
def _getattr_preserve_none(obj: Any, name: str) -> Any
Get attribute with dict fallback, preserving None values.
Like _safe_getattr but preserves None values instead of converting to empty string. Used for optional chaining (?.) so that null coalescing (??) can work correctly.
Resolution order matches _safe_getattr: dicts try subscript first.
Complexity: O(1)
Parameters
| Name | Type | Description |
|---|---|---|
obj |
— |
|
name |
— |
Returns
Any
__repr__
0
str
▼
__repr__
0
str
▼
def __repr__(self) -> str
Returns
str
RenderedTemplate
3
▼
Lazy rendered template with streaming support.
Wraps a Template + context pair. Supports both full…
RenderedTemplate
3
▼
Lazy rendered template with streaming support.
Wraps a Template + context pair. Supports both full rendering
viastr() and chunk-by-chunk iteration via for chunk in rt.
Methods
Internal Methods 3 ▼
__init__
2
▼
__init__
2
▼
def __init__(self, template: Template, context: dict[str, Any])
Parameters
| Name | Type | Description |
|---|---|---|
template |
— |
|
context |
— |
__str__
0
str
▼
Render and return full string.
__str__
0
str
▼
def __str__(self) -> str
Returns
str
__iter__
0
▼
Iterate over rendered HTML chunks via render_stream().
__iter__
0
▼
def __iter__(self)
Functions
_wrap_blocks_if_cached
2
dict[str, Any] | CachedB…
▼
Wrap blocks with CachedBlocksDict if render context has cached blocks.
_wrap_blocks_if_cached
2
dict[str, Any] | CachedB…
▼
def _wrap_blocks_if_cached(blocks: dict[str, Any], render_ctx: RenderContext) -> dict[str, Any] | CachedBlocksDict
Parameters
| Name | Type | Description |
|---|---|---|
blocks |
dict[str, Any] |
|
render_ctx |
RenderContext |
Returns
dict[str, Any] | CachedBlocksDict