jinja2.Template

class jinja2.Template[source]

The central template object. This class represents a compiled template and is used to evaluate it.

Normally the template object is generated from an Environment but it also has a constructor that makes it possible to create a template instance directly using the constructor. It takes the same arguments as the environment constructor but it’s not possible to specify a loader.

Every template object has a few methods and members that are guaranteed to exist. However it’s important that a template object should be considered immutable. Modifications on the object are not supported.

Template objects created from the constructor rather than an environment do have an environment attribute that points to a temporary environment that is probably shared with other templates created with the constructor and compatible settings.

>>> template = Template('Hello {{ name }}!')
>>> template.render(name='John Doe') == u'Hello John Doe!'
True
>>> stream = template.stream(name='John Doe')
>>> next(stream) == u'Hello John Doe!'
True
>>> next(stream)
Traceback (most recent call last):
    ...
StopIteration

Methods

from_code(environment, code, globals[, uptodate]) Creates a template object from compiled code and the globals.
from_module_dict(environment, module_dict, ...) Creates a template object from a module.
generate(*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.
get_corresponding_lineno(lineno) Return the source line number of a line number in the generated bytecode as they are not in sync.
make_module([vars, shared, locals]) This method works like the module attribute when called without arguments but it will evaluate the template on every call rather than caching it.
new_context([vars, shared, locals]) Create a new Context for this template.
render(*args, **kwargs) This method accepts the same arguments as the dict constructor: A dict, a dict subclass or some keyword arguments.
stream(*args, **kwargs) Works exactly like generate() but returns a TemplateStream.

Attributes

debug_info The debug info mapping.
is_up_to_date If this variable is False there is a newer version available.
module The template as module.