High Level API
The high-level API is the API you will use in the application to load andrender Jinja2 templates. The Low Level API on the other side is onlyuseful if you want to dig deeper into Jinja2 or develop extensions.
- class
jinja2.
Environment
([options]) - The core component of Jinja is the Environment. It containsimportant shared variables like configuration, filters, tests,globals and others. Instances of this class may be modified ifthey are not shared and if no template was loaded so far.Modifications on environments after the first template was loadedwill lead to surprising effects and undefined behavior.
Here are the possible initialization parameters:
- block_start_string
The string marking the beginning of a block. Defaults to
'{%'
.- block_end_string
The string marking the end of a block. Defaults to
'%}'
.- variable_start_string
The string marking the beginning of a print statement.Defaults to
'{{'
.- variable_end_string
The string marking the end of a print statement. Defaults to
'}}'
.- comment_start_string
The string marking the beginning of a comment. Defaults to
'{#'
.- comment_end_string
The string marking the end of a comment. Defaults to
'#}'
.- line_statement_prefix
If given and a string, this will be used as prefix for line basedstatements. See also Line Statements.
- line_comment_prefix
If given and a string, this will be used as prefix for line basedcomments. See also Line Statements.
Changelog
New in version 2.2.
- trim_blocks
If this is set to
True
the first newline after a block isremoved (block, not variable tag!). Defaults to False.- lstrip_blocks
If this is set to
True
leading spaces and tabs are strippedfrom the start of a line to a block. Defaults to False.- newline_sequence
The sequence that starts a newline. Must be one of
'\r'
,'\n'
or'\r\n'
. The default is'\n'
which is auseful default for Linux and OS X systems as well as webapplications.- keep_trailing_newline
Preserve the trailing newline when rendering templates.The default is
False
, which causes a single newline,if present, to be stripped from the end of the template.Changelog
New in version 2.7.
- extensions
List of Jinja extensions to use. This can either be import pathsas strings or extension classes. For more information have alook at the extensions documentation.
- optimized
should the optimizer be enabled? Default is
True
.- undefined
Undefined
or a subclass of it that is used to representundefined values in the template.- finalize
A callable that can be used to process the result of a variableexpression before it is output. For example one can convert
None
implicitly into an empty string here.- autoescape
If set to
True
the XML/HTML autoescaping feature is enabled bydefault. For more details about autoescaping seeMarkup
. As of Jinja 2.4 this can alsobe a callable that is passed the template name and has toreturnTrue
orFalse
depending on autoescape should beenabled by default.Changelog
Changed in version 2.4: autoescape can now be a function
- loader
The template loader for this environment.
- cache_size
The size of the cache. Per default this is
400
which meansthat if more than 400 templates are loaded the loader will cleanout the least recently used template. If the cache size is set to0
templates are recompiled all the time, if the cache size is-1
the cache will not be cleaned.Changelog
Changed in version 2.8: The cache size was increased to 400 from a low 50.
- auto_reload
Some loaders load templates from locations where the templatesources may change (ie: file system or database). If
auto_reload
is set toTrue
(default) every time a template isrequested the loader checks if the source changed and if yes, itwill reload the template. For higher performance it’s possible todisable that.- bytecode_cache
If set to a bytecode cache object, this object will provide acache for the internal Jinja bytecode so that templates don’thave to be parsed if they were not changed.
See Bytecode Cache for more information.
- enable_async
If set to true this enables async template execution which allowsyou to take advantage of newer Python features. This requiresPython 3.6 or later.
shared
If a template was created by using the
Template
constructoran environment is created automatically. These environments arecreated as shared environments which means that multiple templatesmay have the same anonymous environment. For all shared environmentsthis attribute is True, else False.If the environment is sandboxed this attribute is True. For thesandbox mode have a look at the documentation for the
SandboxedEnvironment
.A dict of filters for this environment. As long as no template wasloaded it’s safe to add new filters or remove old. For custom filterssee Custom Filters. For valid filter names have a look atNotes on Identifiers.
A dict of test functions for this environment. As long as notemplate was loaded it’s safe to modify this dict. For custom testssee Custom Tests. For valid test names have a look atNotes on Identifiers.
A dict of global variables. These variables are always availablein a template. As long as no template was loaded it’s safeto modify this dict. For more details see The Global Namespace.For valid object names have a look at Notes on Identifiers.
A dictionary with Policies. These can be reconfigured tochange the runtime behavior or certain template features. Usuallythese are security related.
The class used for code generation. This should not be changedin most cases, unless you need to modify the Python code atemplate compiles to.
The context used for templates. This should not be changedin most cases, unless you need to modify internals of howtemplate variables are handled. For details, see
Context
.- Create a new overlay environment that shares all the data with thecurrent environment except for cache and the overridden attributes.Extensions cannot be removed for an overlayed environment. An overlayedenvironment automatically gets all the extensions of the environment itis linked to plus optional extra extensions.
Creating overlays should happen after the initial environment was setup completely. Not all attributes are truly linked, some are justcopied over so modifications on the original environment may not shinethrough.
undefined
([hint, obj, name, exc])- Creates a new
Undefined
object for name. This is usefulfor filters or functions that may return undefined objects forsome operations. All parameters except of hint should be providedas keyword parameters for better readability. The hint is used aserror message for the exception if provided, otherwise the errormessage will be generated from obj and name automatically. The exceptionprovided as exc is raised if something with the generated undefinedobject is done that the undefined object does not allow. The defaultexception isUndefinedError
. If a hint is provided thename may be omitted.
The most common way to create an undefined object is by providinga name only:
return environment.undefined(name='some_name')
This means that the name some_name is not defined. If the namewas from an attribute of an object it makes sense to tell theundefined object the holder object to improve the error message:
if not hasattr(obj, 'attr'):
return environment.undefined(obj=obj, name='attr')
For a more complex example you can provide a hint. For examplethe first()
filter creates an undefined object that way:
return environment.undefined('no first item, sequence was empty')
If it the name or obj is known (for example because an attributewas accessed) it should be passed to the undefined object, even ifa custom hint is provided. This gives undefined objects thepossibility to enhance the error message.
Changelog
New in version 2.5.
compileexpression
(_source, undefined_to_none=True)- A handy helper method that returns a callable that accepts keywordarguments that appear as variables in the expression. If called itreturns the result of the expression.
This is useful if applications want to use the same rules as Jinjain template “configuration files” or similar situations.
Example usage:
>>> env = Environment()
>>> expr = env.compile_expression('foo == 42')
>>> expr(foo=23)
False
>>> expr(foo=42)
True
Per default the return value is converted to None if theexpression returns an undefined value. This can be changedby setting undefined_to_none to False.
>>> env.compile_expression('var')() is None
True
>>> env.compile_expression('var', undefined_to_none=False)()
Undefined
Changelog
New in version 2.1.
compiletemplates
(_target, extensions=None, filter_func=None, zip='deflated', log_function=None, ignore_errors=True, py_compile=False)- Finds all the templates the loader can find, compiles themand stores them in target. If zip is None, instead of in azipfile, the templates will be stored in a directory.By default a deflate zip algorithm is used. To switch tothe stored algorithm, zip can be set to
'stored'
.
extensions and filter_func are passed to list_templates()
.Each template returned will be compiled to the target folder orzipfile.
By default template compilation errors are ignored. In case alog function is provided, errors are logged. If you want templatesyntax errors to abort the compilation you can set ignore_errors_to _False and you will get an exception on syntax errors.
If py_compile is set to True .pyc files will be written to thetarget instead of standard .py files. This flag does not do anythingon pypy and Python 3 where pyc files are not picked up by itself anddon’t give much benefit.
Changelog
New in version 2.4.
extend
(**attributes)Add the items to the instance of the environment if they do not existyet. This is used by extensions to registercallbacks and configuration values without breaking inheritance.
Load a template from a string. This parses the source given andreturns a
Template
object.getor_select_template
(_template_name_or_list, parent=None, globals=None)- Does a typecheck and dispatches to
select_template()
if an iterable of template names is given, otherwise toget_template()
.
Changelog
New in version 2.3.
gettemplate
(_name, parent=None, globals=None)- Load a template from the loader. If a loader is configured thismethod asks the loader for the template and returns a
Template
.If the parent parameter is not None,join_path()
is calledto get the real template name before loading.
The globals parameter can be used to provide template wide globals.These variables are available in the context at render time.
If the template does not exist a TemplateNotFound
exception israised.
Changelog
Changed in version 2.4: If name is a Template
object it is returned from thefunction unchanged.
joinpath
(_template, parent)- Join a template with the parent. By default all the lookups arerelative to the loader root so this method returns the _template_parameter unchanged, but if the paths should be relative to theparent template, this function can be used to calculate the realtemplate name.
Subclasses may override this method and implement template pathjoining here.
listtemplates
(_extensions=None, filter_func=None)- Returns a list of templates for this environment. This requiresthat the loader supports the loader’s
list_templates()
method.
If there are other files in the template folder besides theactual templates, the returned list can be filtered. There are twoways: either extensions is set to a list of file extensions fortemplates, or a filter_func can be provided which is a callable thatis passed a template name and should return True if it should end upin the result list.
If the loader does not support that, a TypeError
is raised.
Changelog
New in version 2.4.
selecttemplate
(_names, parent=None, globals=None)- Works like
get_template()
but tries a number of templatesbefore it fails. If it cannot find any of the templates, it willraise aTemplatesNotFound
exception.
Changelog
Changed in version 2.4: If names contains a Template
object it is returnedfrom the function unchanged.
New in version 2.3.
- class
jinja2.
Template
- The central template object. This class represents a compiled templateand is used to evaluate it.
Normally the template object is generated from an Environment
butit also has a constructor that makes it possible to create a templateinstance directly using the constructor. It takes the same arguments asthe environment constructor but it’s not possible to specify a loader.
Every template object has a few methods and members that are guaranteedto exist. However it’s important that a template object should beconsidered immutable. Modifications on the object are not supported.
Template objects created from the constructor rather than an environmentdo have an environment attribute that points to a temporary environmentthat is probably shared with other templates created with the constructorand 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
globals
The dict with the globals of that template. It’s unsafe to modifythis dict as it may be shared with other templates or the environmentthat loaded the template.
The loading name of the template. If the template was loaded from astring this is None.
The filename of the template on the file system if it was loaded fromthere. Otherwise this is None.
- This method accepts the same arguments as the dict constructor:A dict, a dict subclass or some keyword arguments. If no argumentsare 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 unicode string.
generate
([context])- For very large templates it can be useful to not render the wholetemplate at once but evaluate each statement after another and yieldpiece for piece. This method basically does exactly that and returnsa generator that yields one item after another as unicode strings.
It accepts the same arguments as render()
.
stream
([context])Works exactly like
generate()
but returns aTemplateStream
.- This works similar to
render()
but returns a coroutinethat when awaited returns the entire rendered template string. Thisrequires the async feature to be enabled.
Example usage:
await template.render_async(knights='that say nih; asynchronously')
generateasync
([_context])An async version of
generate()
. Works very similarly butreturns an async iterator instead.This method works like the
module
attribute when calledwithout arguments but it will evaluate the template on every callrather than caching it. It’s also possible to providea dict which is then used as context. The arguments are the sameas for thenew_context()
method.- The template as module. This is used for imports in thetemplate runtime but is also useful if one wants to accessexported 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.
- class
jinja2.environment.
TemplateStream
- A template stream works pretty much like an ordinary python generatorbut it can buffer multiple items to reduce the number of total iterations.Per default the output is unbuffered which means that for every unbufferedinstruction in the template one unicode string is yielded.
If buffering is enabled with a buffer size of 5, five items are combinedinto a new unicode string. This is mainly useful if you are streamingbig templates to a client via WSGI which flushes after each iteration.
disable_buffering
()Disable the output buffering.
- Dump the complete stream into a file or file-like object.Per default unicode strings are written, if you want to encodebefore writing specify an encoding.
Example usage:
Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')