class documentation

class Template:

Known subclasses: jinja2.nativetypes.NativeTemplate

View In Hierarchy

A compiled template that can be rendered.

Use the methods on Environment to create or load templates. The environment is used to configure how templates are compiled and behave.

It is also possible to create a template object directly. This is not usually recommended. The constructor takes most of the same arguments as Environment. All templates created with the same environment arguments share the same ephemeral Environment instance behind the scenes.

A template object should be considered immutable. Modifications on the object are not supported.

Class Method from​_code Creates a template object from compiled code and the globals. This is used by the loaders and environment to create a template object.
Class Method from​_module​_dict Creates a template object from a module. This is used by the module loader to create a template object.
Class Method ​_from​_namespace Undocumented
Method __new__ Undocumented
Method __repr__ Undocumented
Method ​_get​_default​_module No summary
Async Method ​_get​_default​_module​_async Undocumented
Method generate No summary
Async Method generate​_async An async version of generate. Works very similarly but returns an async iterator instead.
Method get​_corresponding​_lineno Return the source line number of a line number in the generated bytecode as they are not in sync.
Method make​_module No summary
Async Method make​_module​_async No summary
Method new​_context No summary
Method render This method accepts the same arguments as the dict constructor: A dict, a dict subclass or some keyword arguments. If no arguments are given the context will be empty. These two calls do the same:
Async Method render​_async This works similar to render but returns a coroutine that when awaited returns the entire rendered template string. This requires the async feature to be enabled.
Method stream Works exactly like generate but returns a TemplateStream.
Class Variable ​_debug​_info Undocumented
Class Variable ​_uptodate Undocumented
Class Variable blocks Undocumented
Class Variable environment Undocumented
Class Variable filename Undocumented
Class Variable globals Undocumented
Class Variable name Undocumented
Class Variable root​_render​_func Undocumented
Instance Variable ​_module Undocumented
Property debug​_info The debug info mapping.
Property is​_up​_to​_date If this variable is False there is a newer version available.
Property module The template as module. This is used for imports in the template runtime but is also useful if one wants to access exported template variables from the Python layer:
@classmethod
def from_code(cls, environment, code, globals, uptodate=None):
Creates a template object from compiled code and the globals. This is used by the loaders and environment to create a template object.
Parameters
environment:EnvironmentUndocumented
code:CodeTypeUndocumented
globals:t.MutableMapping[str, t.Any]Undocumented
uptodate:t.Optional[t.Callable[[], bool]]Undocumented
Returns
TemplateUndocumented
@classmethod
def from_module_dict(cls, environment, module_dict, globals):

Creates a template object from a module. This is used by the module loader to create a template object.

New in version 2.4.
Parameters
environment:EnvironmentUndocumented
module​_dict:t.MutableMapping[str, t.Any]Undocumented
globals:t.MutableMapping[str, t.Any]Undocumented
Returns
TemplateUndocumented
@classmethod
def _from_namespace(cls, environment, namespace, globals):

Undocumented

Parameters
environment:EnvironmentUndocumented
namespace:t.MutableMapping[str, t.Any]Undocumented
globals:t.MutableMapping[str, t.Any]Undocumented
Returns
TemplateUndocumented
def __new__(cls, source, block_start_string=BLOCK_START_STRING, block_end_string=BLOCK_END_STRING, variable_start_string=VARIABLE_START_STRING, variable_end_string=VARIABLE_END_STRING, comment_start_string=COMMENT_START_STRING, comment_end_string=COMMENT_END_STRING, line_statement_prefix=LINE_STATEMENT_PREFIX, line_comment_prefix=LINE_COMMENT_PREFIX, trim_blocks=TRIM_BLOCKS, lstrip_blocks=LSTRIP_BLOCKS, newline_sequence=NEWLINE_SEQUENCE, keep_trailing_newline=KEEP_TRAILING_NEWLINE, extensions=(), optimized=True, undefined=Undefined, finalize=None, autoescape=False, enable_async=False):

Undocumented

Parameters
source:t.Union[str, nodes.Template]Undocumented
block​_start​_string:strUndocumented
block​_end​_string:strUndocumented
variable​_start​_string:strUndocumented
variable​_end​_string:strUndocumented
comment​_start​_string:strUndocumented
comment​_end​_string:strUndocumented
line​_statement​_prefix:t.Optional[str]Undocumented
line​_comment​_prefix:t.Optional[str]Undocumented
trim​_blocks:boolUndocumented
lstrip​_blocks:boolUndocumented
newline​_sequence:te.Literal['\n', '\r\n', '\r']Undocumented
keep​_trailing​_newline:boolUndocumented
extensions:t.Sequence[t.Union[str, t.Type[Extension]]]Undocumented
optimized:boolUndocumented
undefined:t.Type[Undefined]Undocumented
finalize:t.Optional[t.Callable[..., t.Any]]Undocumented
autoescape:t.Union[bool, t.Callable[[t.Optional[str]], bool]]Undocumented
enable​_async:boolUndocumented
Returns
t.AnyUndocumented
def __repr__(self):

Undocumented

Returns
strUndocumented
@internalcode
def _get_default_module(self, ctx=None):

If a context is passed in, this means that the template was imported. Imported templates have access to the current template's globals by default, but they can only be accessed via the context during runtime.

If there are new globals, we need to create a new module because the cached module is already rendered and will not have access to globals from the current context. This new module is not cached because the template can be imported elsewhere, and it should have access to only the current template's globals.

Parameters
ctx:t.Optional[Context]Undocumented
Returns
TemplateModuleUndocumented
async def _get_default_module_async(self, ctx=None):

Undocumented

Parameters
ctx:t.Optional[Context]Undocumented
Returns
TemplateModuleUndocumented
def generate(self, *args, **kwargs):

For very large templates it can be useful to not render the whole template at once but evaluate each statement after another and yield piece for piece. This method basically does exactly that and returns a generator that yields one item after another as strings.

It accepts the same arguments as render.

Parameters
*args:t.AnyUndocumented
**kwargs:t.AnyUndocumented
Returns
t.Iterator[str]Undocumented
async def generate_async(self, *args, **kwargs):
An async version of generate. Works very similarly but returns an async iterator instead.
Parameters
*args:t.AnyUndocumented
**kwargs:t.AnyUndocumented
Returns
t.AsyncIterator[str]Undocumented
def get_corresponding_lineno(self, lineno):
Return the source line number of a line number in the generated bytecode as they are not in sync.
Parameters
lineno:intUndocumented
Returns
intUndocumented
def make_module(self, vars=None, shared=False, locals=None):
This method works like the module attribute when called without arguments but it will evaluate the template on every call rather than caching it. It's also possible to provide a dict which is then used as context. The arguments are the same as for the new_context method.
Parameters
vars:t.Optional[t.Dict[str, t.Any]]Undocumented
shared:boolUndocumented
locals:t.Optional[t.Mapping[str, t.Any]]Undocumented
Returns
TemplateModuleUndocumented
async def make_module_async(self, vars=None, shared=False, locals=None):
As template module creation can invoke template code for asynchronous executions this method must be used instead of the normal make_module one. Likewise the module attribute becomes unavailable in async mode.
Parameters
vars:t.Optional[t.Dict[str, t.Any]]Undocumented
shared:boolUndocumented
locals:t.Optional[t.Mapping[str, t.Any]]Undocumented
Returns
TemplateModuleUndocumented
def new_context(self, vars=None, shared=False, locals=None):

Create a new Context for this template. The vars provided will be passed to the template. Per default the globals are added to the context. If shared is set to True the data is passed as is to the context without adding the globals.

locals can be a dict of local variables for internal usage.

Parameters
vars:t.Optional[t.Dict[str, t.Any]]Undocumented
shared:boolUndocumented
locals:t.Optional[t.Mapping[str, t.Any]]Undocumented
Returns
ContextUndocumented
def render(self, *args, **kwargs):

This method accepts the same arguments as the dict constructor: A dict, a dict subclass or some keyword arguments. If no arguments are given the context will be empty. These two calls do the same:

template.render(knights='that say nih')
template.render({'knights': 'that say nih'})

This will return the rendered template as a string.

Parameters
*args:t.AnyUndocumented
**kwargs:t.AnyUndocumented
Returns
strUndocumented
async def render_async(self, *args, **kwargs):

This works similar to render but returns a coroutine that when awaited returns the entire rendered template string. This requires the async feature to be enabled.

Example usage:

await template.render_async(knights='that say nih; asynchronously')
Parameters
*args:t.AnyUndocumented
**kwargs:t.AnyUndocumented
Returns
strUndocumented
def stream(self, *args, **kwargs):
Works exactly like generate but returns a TemplateStream.
Parameters
*args:t.AnyUndocumented
**kwargs:t.AnyUndocumented
Returns
TemplateStreamUndocumented
_debug_info: str =

Undocumented

_uptodate: t.Optional[t.Callable[[], bool]] =

Undocumented

blocks: t.Dict[str, t.Callable[[Context], t.Iterator[str]]] =

Undocumented

environment: Environment =

Undocumented

filename: t.Optional[str] =

Undocumented

globals: t.MutableMapping[str, t.Any] =

Undocumented

name: t.Optional[str] =

Undocumented

root_render_func: t.Callable[[Context], t.Iterator[str]] =

Undocumented

_module =

Undocumented

@property
debug_info: t.List[t.Tuple[int, int]] =
The debug info mapping.
@property
is_up_to_date: bool =
If this variable is False there is a newer version available.
@property
module: TemplateModule =

The template as module. This is used for imports in the template runtime but is also useful if one wants to access exported template variables from the Python layer:

>>> t = Template('{% macro foo() %}42{% endmacro %}23')
>>> str(t.module)
'23'
>>> t.module.foo() == u'42'
True

This attribute is not available if async mode is enabled.