API¶

This document describes the API to Jinja2 and not the template language. Itwill be most useful as reference to those implementing the template interfaceto the application and not those who are creating Jinja2 templates.

Basics¶

Jinja2 uses a central object called the template Environment.Instances of this class are used to store the configuration and global objects,and are used to load templates from the file system or other locations.Even if you are creating templates from strings by using the constructor ofTemplate class, an environment is created automatically for you,albeit a shared one.

Most applications will create one Environment object on applicationinitialization and use that to load templates. In some cases however, it’suseful to have multiple environments side by side, if different configurationsare in use.

The simplest way to configure Jinja2 to load templates for your applicationlooks roughly like this:

  1. from jinja2 import Environment, PackageLoader, select_autoescape
  2. env = Environment(
  3. loader=PackageLoader('yourapplication', 'templates'),
  4. autoescape=select_autoescape(['html', 'xml'])
  5. )

This will create a template environment with the default settings and aloader that looks up the templates in the templates folder inside theyourapplication python package. Different loaders are availableand you can also write your own if you want to load templates from adatabase or other resources. This also enables autoescaping for HTML andXML files.

To load a template from this environment you just have to call theget_template() method which then returns the loaded Template:

  1. template = env.get_template('mytemplate.html')

To render it with some variables, just call the render() method:

  1. print template.render(the='variables', go='here')

Using a template loader rather than passing strings to Templateor Environment.from_string() has multiple advantages. Besides beinga lot easier to use it also enables template inheritance.

Notes on Autoescaping

In future versions of Jinja2 we might enable autoescaping by defaultfor security reasons. As such you are encouraged to explicitlyconfigure autoescaping now instead of relying on the default.

Unicode¶

Jinja2 is using Unicode internally which means that you have to pass Unicodeobjects to the render function or bytestrings that only consist of ASCIIcharacters. Additionally newlines are normalized to one end of linesequence which is per default UNIX style (\n).

Python 2.x supports two ways of representing string objects. One is thestr type and the other is the unicode type, both of which extend a typecalled basestring. Unfortunately the default is str which should notbe used to store text based information unless only ASCII characters areused. With Python 2.6 it is possible to make unicode the default on a permodule level and with Python 3 it will be the default.

To explicitly use a Unicode string you have to prefix the string literalwith a u: u'Hänsel und Gretel sagen Hallo'. That way Python willstore the string as Unicode by decoding the string with the characterencoding from the current Python module. If no encoding is specified thisdefaults to ‘ASCII’ which means that you can’t use any non ASCII identifier.

To set a better module encoding add the following comment to the first orsecond line of the Python module using the Unicode literal:

  1. # -*- coding: utf-8 -*-

We recommend utf-8 as Encoding for Python modules and templates as it’spossible to represent every Unicode character in utf-8 and because it’sbackwards compatible to ASCII. For Jinja2 the default encoding of templatesis assumed to be utf-8.

It is not possible to use Jinja2 to process non-Unicode data. The reasonfor this is that Jinja2 uses Unicode already on the language level. Forexample Jinja2 treats the non-breaking space as valid whitespace insideexpressions which requires knowledge of the encoding or operating on anUnicode string.

For more details about Unicode in Python have a look at the excellentUnicode documentation.

Another important thing is how Jinja2 is handling string literals intemplates. A naive implementation would be using Unicode strings forall string literals but it turned out in the past that this is problematicas some libraries are typechecking against str explicitly. For exampledatetime.strftime does not accept Unicode arguments. To not break itcompletely Jinja2 is returning str for strings that fit into ASCII andfor everything else unicode:

  1. >>> m = Template(u"{% set a, b = 'foo', 'föö' %}").module
  2. >>> m.a
  3. 'foo'
  4. >>> m.b
  5. u'f\xf6\xf6'

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.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.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 convertNone 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 toreturn True or False depending on autoescape should beenabled by default.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.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). Ifautoreload is set to True (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.
sandboxed

If the environment is sandboxed this attribute is True. For thesandbox mode have a look at the documentation for theSandboxedEnvironment.
filters

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.
tests

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.
globals

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.
policies

A dictionary with Policies. These can be reconfigured tochange the runtime behavior or certain template features. Usuallythese are security related.
codegenerator_class

The class used for code generation. This should not be changedin most cases, unless you need to modify the Python code atemplate compiles to.
context_class

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, seeContext.
overlay([_options])

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 is UndefinedError. If a hint is provided thename may be omitted.

The most common way to create an undefined object is by providinga name only:



  1. return environment.undefined(name='somename')




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:



  1. 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:



  1. 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.
addextension(_extension)

Adds an extension after the environment was created.


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:



  1. >>> env = Environment()
    >>> expr = env.compileexpression('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.



  1. >>> env.compileexpression('var')() is None
    True
    >>> env.compile_expression('var', undefined_to_none=False)()
    Undefined





New in version 2.1.

compile_templates(_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.


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.
fromstring(_source, globals=None, template_class=None)

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().


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.


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.
list_templates(_extensions=None, filter_func=None)

Returns a list of templates for this environment. This requiresthat the loader supports the loader’slisttemplates() 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.


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 a TemplatesNotFound exception.


New in version 2.3.



Changed in version 2.4: If names contains a Template object it is returnedfrom the function unchanged.

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.



  1. >>> 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.
name

The loading name of the template. If the template was loaded from astring this is None.
filename

The filename of the template on the file system if it was loaded fromthere. Otherwise this is None.
render([context])

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:



  1. 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.
renderasync([_context])

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:



  1. await template.renderasync(knights='that say nih; asynchronously')



generate_async([_context])

An async version of generate(). Works very similarly butreturns an async iterator instead.
makemodule(_vars=None, shared=False, locals=None)

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 the new_context() method.
module

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:



  1. >>> 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.
disablebuffering()

Disable the output buffering.
dump(_fp, encoding=None, errors='strict')

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:



  1. Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')



enablebuffering(_size=5)

Enable buffering. Buffer size items before yielding them.

Autoescaping¶

Changed in version 2.4.

Jinja2 now comes with autoescaping support. As of Jinja 2.9 theautoescape extension is removed and built-in. However autoescaping isnot yet enabled by default though this will most likely change in thefuture. It’s recommended to configure a sensible default forautoescaping. This makes it possible to enable and disable autoescapingon a per-template basis (HTML versus text for instance).

jinja2.selectautoescape(_enabled_extensions=('html', 'htm', 'xml'), disabled_extensions=(), default_for_string=True, default=False)

Intelligently sets the initial value of autoescaping based on thefilename of the template. This is the recommended way to configureautoescaping if you do not want to write a custom function yourself.

If you want to enable it for all templates created from strings orfor all templates with .html and .xml extensions:



  1. from jinja2 import Environment, selectautoescape
    env = Environment(autoescape=select_autoescape(
    enabled_extensions=('html', 'xml'),
    default_for_string=True,
    ))




Example configuration to turn it on at all times except if the templateends with
.txt:



  1. from jinja2 import Environment, select_autoescape
    env = Environment(autoescape=select_autoescape(
    disabled_extensions=('txt',),
    default_for_string=True,
    default=True,
    ))




The _enabled_extensions
is an iterable of all the extensions thatautoescaping should be enabled for. Likewise disabled_extensions isa list of all templates it should be disabled for. If a template isloaded from a string then the default from default_for_string is used.If nothing matches then the initial value of autoescaping is set to thevalue of default.

For security reasons this function operates case insensitive.


New in version 2.9.


Here a recommended setup that enables autoescaping for templates endingin '.html', '.htm' and '.xml' and disabling it by defaultfor all other extensions. You can use the select_autoescape()function for this:



  1. from jinja2 import Environment, selectautoescape
    env = Environment(autoescape=select_autoescape(['html', 'htm', 'xml']),
    loader=PackageLoader('mypackage'))




The select_autoescape() function returns a function thatworks rougly like this:



  1. def autoescape(template_name):
    if template_name is None:
    return False
    if template_name.endswith(('.html', '.htm', '.xml'))




When implementing a guessing autoescape function, make sure you alsoaccept _None
as valid template name. This will be passed when generatingtemplates from strings. You should always configure autoescaping asdefaults in the future might change.

Inside the templates the behaviour can be temporarily changed by usingthe autoescape block (see Autoescape Overrides).



## Notes on Identifiers¶

Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have tomatch [a-zA-Z][a-zA-Z0-9]. As a matter of fact non ASCII charactersare currently not allowed. This limitation will probably go away as soon asunicode identifiers are fully specified for Python 3.

Filters and tests are looked up in separate namespaces and have slightlymodified identifier syntax. Filters and tests may contain dots to groupfilters and tests by topic. For example it’s perfectly valid to add afunction into the filter dict and call it to.unicode. The regularexpression for filter and test identifiers is[a-zA-Z][a-zA-Z0-9]
(.[a-zA-Z][a-zA-Z0-9])`.



## Undefined Types¶

These classes can be used as undefined types. The Environmentconstructor takes an undefined parameter that can be one of those classesor a custom subclass of Undefined. Whenever the template engine isunable to look up a name or access an attribute one of those objects iscreated and returned. Some operations on undefined values are then allowed,others fail.

The closest to regular Python behavior is the StrictUndefined whichdisallows all operations beside testing if it’s an undefined object.
class jinja2.Undefined

The default undefined type. This undefined type can be printed anditerated over, but every other access will raise an jinja2.exceptions.UndefinedError:



  1. >>> foo = Undefined(name='foo')
    >>> str(foo)
    ''
    >>> not foo
    True
    >>> foo + 42
    Traceback (most recent call last):

    jinja2.exceptions.UndefinedError: 'foo' is undefined



undefined_hint

Either _None
or an unicode string with the error message forthe undefined object.
undefined_obj

Either _None
or the owner object that caused the undefined objectto be created (for example because an attribute does not exist).
undefined_name

The name for the undefined variable / attribute or just _None_if no such information exists.
_undefined_exception

The exception that the undefined object wants to raise. Thisis usually one of UndefinedError or SecurityError.
_fail_with_undefined_error(args, kwargs)

When called with any arguments this method raises_undefined_exception with an error message generatedfrom the undefined hints stored on the undefined object.
_class jinja2.DebugUndefined

An undefined that returns the debug info when printed.



  1. >>> foo = DebugUndefined(name='foo')
    >>> str(foo)
    '{{ foo }}'
    >>> not foo
    True
    >>> foo + 42
    Traceback (most recent call last):

    jinja2.exceptions.UndefinedError: 'foo' is undefined



class jinja2.StrictUndefined

An undefined that barks on print and iteration as well as booleantests and all kinds of comparisons. In other words: you can do nothingwith it except checking if it’s defined using the defined test.



  1. >>> foo = StrictUndefined(name='foo')
    >>> str(foo)
    Traceback (most recent call last):

    jinja2.exceptions.UndefinedError: 'foo' is undefined
    >>> not foo
    Traceback (most recent call last):

    jinja2.exceptions.UndefinedError: 'foo' is undefined
    >>> foo + 42
    Traceback (most recent call last):

    jinja2.exceptions.UndefinedError: 'foo' is undefined




There is also a factory function that can decorate undefined objects toimplement logging on failures:
jinja2.makelogging_undefined(_logger=None, base=None)

Given a logger object this returns a new undefined class that willlog certain failures. It will log iterations and printing. If nologger is given a default logger is created.

Example:



  1. logger = logging.getLogger(name)
    LoggingUndefined = make_logging_undefined(
    logger=logger,
    base=Undefined
    )





New in version 2.8.


|Parameters:
|——-
|
-
logger – the logger to use. If not provided, a default loggeris created.
-
base – the base class to add logging functionality to. Thisdefaults to Undefined.


Undefined objects are created by calling undefined.


Implementation

Undefined objects are implemented by overriding the specialunderscore methods. For example the default Undefinedclass implements unicode in a way that it returns an emptystring, however int and others still fail with an exception. Toallow conversion to int by returning 0 you can implement your own:



  1. class NullUndefined(Undefined):
    def int(self):
    return 0
    def float(self):
    return 0.0




To disallow a method, just override it and raise_undefined_exception. Because this is a very commonidom in undefined objects there is the helper method_fail_with_undefined_error() that does the error raisingautomatically. Here a class that works like the regular Undefinedbut chokes on iteration:



  1. class NonIterableUndefined(Undefined):
    iter = Undefined.fail_with_undefined_error







## The Context¶
_class jinja2.runtime.Context

The template context holds the variables of a template. It stores thevalues passed to the template and also the names the template exports.Creating instances is neither supported nor useful as it’s createdautomatically at various stages of the template evaluation and should notbe created by hand.

The context is immutable. Modifications on parent
must not**happen and modifications on vars are allowed from generatedtemplate code only. Template filters and global functions marked ascontextfunction()s get the active context passed as first argumentand are allowed to access the context read-only.

The template context supports read only dict operations (get,keys, values, items, iterkeys, itervalues, iteritems,getitem, contains). Additionally there is a resolve()method that doesn’t fail with a KeyError but returns anUndefined object for missing variables.
parent

A dict of read only, global variables the template looks up. Thesecan either come from another Context, from theEnvironment.globals or Template.globals or pointsto a dict created by combining the globals with the variablespassed to the render function. It must not be altered.
vars

The template local variables. This list contains environment andcontext functions from the parent scope as well as localmodifications and exported variables from the template. The templatewill modify this dict during template evaluation but filters andcontext functions are not allowed to modify it.
environment

The environment that loaded the template.
exportedvars

This set contains all the names the template exports. The values forthe names are in the vars dict. In order to get a copy of theexported variables as dict, get_exported() can be used.
name

The load name of the template owning this context.
blocks

A dict with the current mapping of blocks in the template. The keysin this dict are the names of the blocks, and the values a list ofblocks registered. The last item in each list is the current activeblock (latest in the inheritance chain).
eval_ctx

The current Evaluation Context.
call(_callable, _args, **kwargs)

Call the callable with the arguments and keyword argumentsprovided but inject the active context or environment as firstargument if the callable is a contextfunction() orenvironmentfunction().
get_all()

Return the complete context as dict including the exportedvariables. For optimizations reasons this might not return anactual copy so be careful with using it.
get_exported()

Get a new dict with the exported variables.
resolve(_key)

Looks up a variable like getitem or get but returns anUndefined object with the name of the name looked up.

Implementation

Context is immutable for the same reason Python’s frame locals areimmutable inside functions. Both Jinja2 and Python are not using thecontext / frame locals as data storage for variables but only as primarydata source.

When a template accesses a variable the template does not define, Jinja2looks up the variable in the context, after that the variable is treatedas if it was defined in the template.

Loaders¶

Loaders are responsible for loading templates from a resource such as thefile system. The environment will keep the compiled modules in memory likePython’s sys.modules. Unlike sys.modules however this cache is limited insize by default and templates are automatically reloaded.All loaders are subclasses of BaseLoader. If you want to create yourown loader, subclass BaseLoader and override get_source.

class jinja2.BaseLoader

Baseclass for all loaders. Subclass this and override get_source toimplement a custom loading mechanism. The environment provides aget_template method that calls the loader’s load method to get theTemplate object.

A very basic example for a loader that looks up templates on the filesystem could look like this:



  1. from jinja2 import BaseLoader, TemplateNotFound
    from os.path import join, exists, getmtime

    class MyLoader(BaseLoader):

    def init(self, path):
    self.path = path

    def getsource(self, environment, template):
    path = join(self.path, template)
    if not exists(path):
    raise TemplateNotFound(template)
    mtime = getmtime(path)
    with file(path) as f:
    source = f.read().decode('utf-8')
    return source, path, lambda: mtime == getmtime(path)



get_source(_environment, template)

Get the template source, filename and reload helper for a template.It’s passed the environment and template name and has to return atuple in the form (source, filename, uptodate) or raise aTemplateNotFound error if it can’t locate the template.

The source part of the returned tuple must be the source of thetemplate as unicode string or a ASCII bytestring. The filename shouldbe the name of the file on the filesystem if it was loaded from there,otherwise None. The filename is used by python for the tracebacksif no loader extension is used.

The last item in the tuple is the uptodate function. If autoreloading is enabled it’s always called to check if the templatechanged. No arguments are passed so the function must store theold state somewhere (for example in a closure). If it returns False_the template will be reloaded.
load(_environment, name, globals=None)

Loads a template. This method looks up the template in the cacheor loads one by calling get_source(). Subclasses should notoverride this method as loaders working on collections of otherloaders (such as PrefixLoader or ChoiceLoader)will not call this method but get_source directly.

Here a list of the builtin loaders Jinja2 provides:
class jinja2.FileSystemLoader(searchpath, encoding='utf-8', followlinks=False)

Loads templates from the file system. This loader can find templatesin folders on the file system and is the preferred way to load them.

The loader takes the path to the templates as string, or if multiplelocations are wanted a list of them which is then looked up in thegiven order:



  1. >>> loader = FileSystemLoader('/path/to/templates')
    >>> loader = FileSystemLoader(['/path/to/templates', '/other/path'])




Per default the template encoding is 'utf-8' which can be changedby setting the encoding parameter to something else.

To follow symbolic links, set the followlinks parameter to True:



  1. >>> loader = FileSystemLoader('/path/to/templates', followlinks=True)





Changed in version 2.8+: The followlinks parameter was added.

class jinja2.PackageLoader(package_name, package_path='templates', encoding='utf-8')

Load templates from python eggs or packages. It is constructed withthe name of the python package and the path to the templates in thatpackage:



  1. loader = PackageLoader('mypackage', 'views')




If the package path is not given, 'templates' is assumed.

Per default the template encoding is 'utf-8' which can be changedby setting the encoding parameter to something else. Due to the natureof eggs it’s only possible to reload templates if the package was loadedfrom the file system and not a zip file.
class jinja2.DictLoader(mapping)

Loads a template from a python dict. It’s passed a dict of unicodestrings bound to template names. This loader is useful for unittesting:



  1. >>> loader = DictLoader({'index.html': 'source here'})




Because auto reloading is rarely useful this is disabled per default.
class jinja2.FunctionLoader(load_func)

A loader that is passed a function which does the loading. Thefunction receives the name of the template and has to return eitheran unicode string with the template source, a tuple in the form (source,
filename, uptodatefunc)
or None if the template does not exist.



  1. >>> def loadtemplate(name):
    if name == 'index.html':
    return '…'

    >>> loader = FunctionLoader(load_template)




The _uptodatefunc
is a function that is called if autoreload is enabledand has to return True if the template is still up to date. For moredetails have a look at BaseLoader.get_source() which has the samereturn value.
class jinja2.PrefixLoader(mapping, delimiter='/')

A loader that is passed a dict of loaders where each loader is boundto a prefix. The prefix is delimited from the template by a slash perdefault, which can be changed by setting the delimiter argument tosomething else:



  1. loader = PrefixLoader({
    'app1': PackageLoader('mypackage.app1'),
    'app2': PackageLoader('mypackage.app2')
    })




By loading 'app1/index.html' the file from the app1 package is loaded,by loading 'app2/index.html' the file from the second.
class jinja2.ChoiceLoader(loaders)

This loader works like the PrefixLoader just that no prefix isspecified. If a template could not be found by one loader the next oneis tried.



  1. >>> loader = ChoiceLoader([
    FileSystemLoader('/path/to/user/templates'),
    FileSystemLoader('/path/to/system/templates')
    ])




This is useful if you want to allow users to override builtin templatesfrom a different location.
class jinja2.ModuleLoader(path)

This loader loads templates from precompiled templates.

Example usage:



  1. >>> loader = ChoiceLoader([
    ModuleLoader('/path/to/compiled/templates'),
    FileSystemLoader('/path/to/templates')
    ])




Templates can be precompiled with Environment.compile_templates().

Bytecode Cache¶

Jinja 2.1 and higher support external bytecode caching. Bytecode caches makeit possible to store the generated bytecode on the file system or a differentlocation to avoid parsing the templates on first use.

This is especially useful if you have a web application that is initialized onthe first request and Jinja compiles many templates at once which slows downthe application.

To use a bytecode cache, instantiate it and pass it to the Environment.

class jinja2.BytecodeCache

To implement your own bytecode cache you have to subclass this classand override load_bytecode() and dump_bytecode(). Both ofthese methods are passed a Bucket.

A very basic bytecode cache that saves the bytecode on the file system:



  1. from os import path

    class MyCache(BytecodeCache):

    def init(self, directory):
    self.directory = directory

    def loadbytecode(self, bucket):
    filename = path.join(self.directory, bucket.key)
    if path.exists(filename):
    with open(filename, 'rb') as f:
    bucket.load_bytecode(f)

    def dump_bytecode(self, bucket):
    filename = path.join(self.directory, bucket.key)
    with open(filename, 'wb') as f:
    bucket.write_bytecode(f)




A more advanced version of a filesystem based bytecode cache is part ofJinja2.
clear()

Clears the cache. This method is not used by Jinja2 but should beimplemented to allow applications to clear the bytecode cache usedby a particular environment.
dump_bytecode(_bucket)

Subclasses have to override this method to write the bytecodefrom a bucket back to the cache. If it unable to do so it must notfail silently but raise an exception.
loadbytecode(_bucket)

Subclasses have to override this method to load bytecode into abucket. If they are not able to find code in the cache for thebucket, it must not do anything.
class jinja2.bccache.Bucket(environment, key, checksum)

Buckets are used to store the bytecode for one template. It’s createdand initialized by the bytecode cache and passed to the loading functions.

The buckets get an internal checksum from the cache assigned and use thisto automatically reject outdated cache material. Individual bytecodecache subclasses don’t have to care about cache invalidation.
environment

The Environment that created the bucket.
key

The unique cache key for this bucket
code

The bytecode if it’s loaded, otherwise None.
bytecodefrom_string(_string)

Load bytecode from a string.
bytecodeto_string()

Return the bytecode as string.
load_bytecode(_f)

Loads bytecode from a file or file like object.
reset()

Resets the bucket (unloads the bytecode).
writebytecode(_f)

Dump the bytecode into the file or file like object passed.

Builtin bytecode caches:
class jinja2.FileSystemBytecodeCache(directory=None, pattern='__jinja2%s.cache')

A bytecode cache that stores bytecode on the filesystem. It acceptstwo arguments: The directory where the cache items are stored and apattern string that is used to build the filename.

If no directory is specified a default cache directory is selected. OnWindows the user’s temp directory is used, on UNIX systems a directoryis created for the user in the system temp directory.

The pattern can be used to have multiple separate caches operate on thesame directory. The default pattern is '__jinja2
%s.cache'. %sis replaced with the cache key.



  1. >>> bcc = FileSystemBytecodeCache('/tmp/jinjacache', '%s.cache')




This bytecode cache supports clearing of the cache using the clear method.
_class jinja2.MemcachedBytecodeCache(client, prefix='jinja2/bytecode/', timeout=None, ignore_memcache_errors=True)

This class implements a bytecode cache that uses a memcache cache forstoring the information. It does not enforce a specific memcache library(tummy’s memcache or cmemcache) but will accept any class that providesthe minimal interface required.

Libraries compatible with this class:

- werkzeug.contrib.cache
- python-memcached
- cmemcache
(Unfortunately the django cache interface is not compatible because itdoes not support storing binary data, only unicode. You can however passthe underlying cache client to the bytecode cache which is availableas django.core.cache.cache._client.)

The minimal interface for the client passed to the constructor is this:
class MinimalClientInterface
set(key, value[, timeout])

Stores the bytecode in the cache. value is a string andtimeout the timeout of the key. If timeout is not provideda default timeout or no timeout should be assumed, if it’sprovided it’s an integer with the number of seconds the cacheitem should exist.
get(key)

Returns the value for the cache key. If the item does notexist in the cache the return value must be None.

The other arguments to the constructor are the prefix for all keys thatis added before the actual cache key and the timeout for the bytecode inthe cache system. We recommend a high (or no) timeout.

This bytecode cache does not support clearing of used items in the cache.The clear method is a no-operation function.


New in version 2.7: Added support for ignoring memcache errors through theignore_memcache_errors parameter.

Async Support¶

Starting with version 2.9, Jinja2 also supports the Python async andawait constructs. As far as template designers go this feature isentirely opaque to them however as a developer you should be aware of howit’s implemented as it influences what type of APIs you can safely exposeto the template environment.

First you need to be aware that by default async support is disabled asenabling it will generate different template code behind the scenes whichpasses everything through the asyncio event loop. This is important tounderstand because it has some impact to what you are doing:

  • template rendering will require an event loop to be set for thecurrent thread (asyncio.get_event_loop needs to return one)
  • all template generation code internally runs async generators whichmeans that you will pay a performance penalty even if the non syncmethods are used!
  • The sync methods are based on async methods if the async mode isenabled which means that render for instance will internally invokerender_async and run it as part of the current event loop until theexecution finished.
    Awaitable objects can be returned from functions in templates and anyfunction call in a template will automatically await the result. Thismeans that you can let provide a method that asynchronously loads datafrom a database if you so desire and from the template designer’s point ofview this is just another function they can call. This means that theawait you would normally issue in Python is implied. However thisonly applies to function calls. If an attribute for instance would be anavaitable object then this would not result in the expected behavior.

Likewise iterations with a for loop support async iterators.

Policies¶

Starting with Jinja 2.9 policies can be configured on the environmentwhich can slightly influence how filters and other template constructsbehave. They can be configured with thepolicies attribute.

Example:

  1. env.policies['urlize.rel'] = 'nofollow noopener'
compiler.asciistr:
This boolean controls on Python 2 if Jinja2 should store ASCII onlyliterals as bytestring instead of unicode strings. This used to bealways enabled for Jinja versions below 2.9 and now can be changed.Traditionally it was done this way since some APIs in Python 2 failedbadly for unicode strings (for instance the datetime strftime API).Now however sometimes the inverse is true (for instance str.format).If this is set to False then all strings are stored as unicodeinternally.
truncate.leeway:
Configures the leeway default for the _truncate filter. Leeway asintroduced in 2.9 but to restore compatibility with older templatesit can be configured to 0 to get the old behavior back. The defaultis 5.
urlize.rel:
A string that defines the items for the rel attribute of generatedlinks with the urlize filter. These items are always added. Thedefault is noopener.
urlize.target:
The default target that is issued for links from the urlize filterif no other target is defined by the call explicitly.
json.dumpsfunction:
If this is set to a value other than _None then the tojson filterwill dump with this function instead of the default one. Note thatthis function should accept arbitrary extra arguments which might bepassed in the future from the filter. Currently the only argumentthat might be passed is indent. The default dump function isjson.dumps.
json.dumpskwargs:
Keyword arguments to be passed to the dump function. The default is{'sort_keys': True}.
ext.i18n.trimmed:
If this is set to _True, {% trans %} blocks of thei18n Extension will always unify linebreaks and surroundingwhitespace as if the trimmed modifier was used.

Utilities¶

These helper functions and classes are useful if you add custom filters orfunctions to a Jinja2 environment.

jinja2.environmentfilter(f)

Decorator for marking environment dependent filters. The currentEnvironment is passed to the filter as first argument.
jinja2.contextfilter(f)

Decorator for marking context dependent filters. The currentContext will be passed as first argument.
jinja2.evalcontextfilter(f)

Decorator for marking eval-context dependent filters. An evalcontext object is passed as first argument. For more informationabout the eval context, see Evaluation Context.


New in version 2.4.

jinja2.environmentfunction(f)

This decorator can be used to mark a function or method as environmentcallable. This decorator works exactly like the contextfunction()decorator just that the first argument is the active Environmentand not context.
jinja2.contextfunction(f)

This decorator can be used to mark a function or method context callable.A context callable is passed the active Context as first argument whencalled from the template. This is useful if a function wants to get accessto the context or functions provided on the context object. For examplea function that returns a sorted list of template variables the currenttemplate exports could look like this:



  1. @contextfunction
    def getexported_names(context):
    return sorted(context.exported_vars)



jinja2.evalcontextfunction(_f)

This decorator can be used to mark a function or method as an evalcontext callable. This is similar to the contextfunction()but instead of passing the context, an evaluation context object ispassed. For more information about the eval context, seeEvaluation Context.


New in version 2.4.

jinja2.escape(s)

Convert the characters &, <, >, ', and " in string s_to HTML-safe sequences. Use this if you need to display text that mightcontain such characters in HTML. This function will not escaped objectsthat do have an HTML representation such as already escaped data.

The return value is a Markup string.
jinja2.clear_caches()

Jinja2 keeps internal caches for environments and lexers. These areused so that Jinja2 doesn’t have to recreate environments and lexers allthe time. Normally you don’t have to care about that but if you aremeasuring memory consumption you may want to clean the caches.
jinja2.is_undefined(_obj)

Check if the object passed is undefined. This does nothing more thanperforming an instance check against Undefined but looks nicer.This can be used for custom filters or tests that want to react toundefined variables. For example a custom default filter can look likethis:



  1. def default(var, default=''):
    if isundefined(var):
    return default
    return var



_class jinja2.Markup([string])

Marks a string as being safe for inclusion in HTML/XML output withoutneeding to be escaped. This implements the html interface a coupleof frameworks and web applications use. Markup is a directsubclass of unicode and provides all the methods of unicode just thatit escapes arguments passed and always returns Markup.

The escape function returns markup objects so that double escaping can’thappen.

The constructor of the Markup class can be used for threedifferent things: When passed an unicode object it’s assumed to be safe,when passed an object with an HTML representation (has an htmlmethod) that representation is used, otherwise the object passed isconverted into a unicode string and then assumed to be safe:



  1. >>> Markup("Hello <em>World</em>!")
    Markup(u'Hello <em>World</em>!')
    >>> class Foo(object):
    def html(self):
    return '<a href="#">foo</a>'

    >>> Markup(Foo())
    Markup(u'<a href="#">foo</a>')




If you want object passed being always treated as unsafe you can use theescape() classmethod to create a Markup object:



  1. >>> Markup.escape("Hello <em>World</em>!")
    Markup(u'Hello &lt;em&gt;World&lt;/em&gt;!')




Operations on a markup string are markup aware which means that allarguments are passed through the escape() function:



  1. >>> em = Markup("<em>%s</em>")
    >>> em % "foo & bar"
    Markup(u'<em>foo &amp; bar</em>')
    >>> strong = Markup("<strong>%(text)s</strong>")
    >>> strong % {'text': '<blink>hacker here</blink>'}
    Markup(u'<strong>&lt;blink&gt;hacker here&lt;/blink&gt;</strong>')
    >>> Markup("<em>Hello</em> ") + "<foo>"
    Markup(u'<em>Hello</em> &lt;foo&gt;')



classmethod escape(s)

Escape the string. Works like escape() with the differencethat for subclasses of Markup this function would return thecorrect subclass.
striptags()

Unescape markup into an text_type string and strip all tags. Thisalso resolves known HTML4 and XHTML entities. Whitespace isnormalized to one:



  1. >>> Markup("Main &raquo; <em>About</em>").striptags()
    u'Main \xbb About'



unescape()

Unescape markup again into an text_type string. This also resolvesknown HTML4 and XHTML entities:



  1. >>> Markup("Main &raquo; <em>About</em>").unescape()
    u'Main \xbb <em>About</em>'



Note

The Jinja2 Markup class is compatible with at least Pylons andGenshi. It’s expected that more template engines and framework will pickup the html concept soon.

Exceptions¶

exception jinja2.TemplateError(message=None)

Baseclass for all template errors.
exception jinja2.UndefinedError(message=None)

Raised if a template tries to operate on Undefined.
exception jinja2.TemplateNotFound(name, message=None)

Raised if a template does not exist.
exception jinja2.TemplatesNotFound(names=(), message=None)

Like TemplateNotFound but raised if multiple templatesare selected. This is a subclass of TemplateNotFoundexception, so just catching the base exception will catch both.


New in version 2.2.

exception jinja2.TemplateSyntaxError(message, lineno, name=None, filename=None)

Raised to tell the user that there is a problem with the template.
message

The error message as utf-8 bytestring.
lineno

The line number where the error occurred
name

The load name for the template as unicode string.
filename

The filename that loaded the template as bytestring in the encodingof the file system (most likely utf-8 or mbcs on Windows systems).

The reason why the filename and error message are bytestrings and notunicode strings is that Python 2.x is not using unicode for exceptionsand tracebacks as well as the compiler. This will change with Python 3.
exception jinja2.TemplateRuntimeError(message=None)

A generic runtime error in the template engine. Under some situationsJinja may raise this exception.
exception jinja2.TemplateAssertionError(message, lineno, name=None, filename=None)

Like a template syntax error, but covers cases where something in thetemplate caused an error at compile time that wasn’t necessarily causedby a syntax error. However it’s a direct subclass ofTemplateSyntaxError and has the same attributes.

Custom Filters¶

Custom filters are just regular Python functions that take the left side ofthe filter as first argument and the arguments passed to the filter asextra arguments or keyword arguments.

For example in the filter {{ 42|myfilter(23) }} the function would becalled with myfilter(42, 23). Here for example a simple filter that canbe applied to datetime objects to format them:

  1. def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
  2. return value.strftime(format)

You can register it on the template environment by updating thefilters dict on the environment:

  1. environment.filters['datetimeformat'] = datetimeformat

Inside the template it can then be used as follows:

  1. written on: {{ article.pub_date|datetimeformat }}
  2. publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}

Filters can also be passed the current template context or environment. Thisis useful if a filter wants to return an undefined value or check the currentautoescape setting. For this purpose three decoratorsexist: environmentfilter(), contextfilter() andevalcontextfilter().

Here a small example filter that breaks a text into HTML line breaks andparagraphs and marks the return value as safe HTML string if autoescaping isenabled:

  1. import re
  2. from jinja2 import evalcontextfilter, Markup, escape
  3.  
  4. _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
  5.  
  6. @evalcontextfilter
  7. def nl2br(eval_ctx, value):
  8. result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', Markup('<br>\n'))
  9. for p in _paragraph_re.split(escape(value)))
  10. if eval_ctx.autoescape:
  11. result = Markup(result)
  12. return result

Context filters work the same just that the first argument is the currentactive Context rather than the environment.

Evaluation Context¶

The evaluation context (short eval context or eval ctx) is a new objectintroduced in Jinja 2.4 that makes it possible to activate and deactivatecompiled features at runtime.

Currently it is only used to enable and disable the automatic escaping butcan be used for extensions as well.

In previous Jinja versions filters and functions were marked asenvironment callables in order to check for the autoescape status from theenvironment. In new versions it’s encouraged to check the setting from theevaluation context instead.

Previous versions:

  1. @environmentfilter
    def filter(env, value):
    result = do_something(value)
    if env.autoescape:
    result = Markup(result)
    return result

In new versions you can either use a contextfilter() and access theevaluation context from the actual context, or use aevalcontextfilter() which directly passes the evaluation context tothe function:

  1. @contextfilter
    def filter(context, value):
    result = do_something(value)
    if context.eval_ctx.autoescape:
    result = Markup(result)
    return result

  2. @evalcontextfilter
    def filter(eval_ctx, value):
    result = do_something(value)
    if eval_ctx.autoescape:
    result = Markup(result)
    return result

The evaluation context must not be modified at runtime. Modificationsmust only happen with a nodes.EvalContextModifier andnodes.ScopedEvalContextModifier from an extension, not on theeval context object itself.

class jinja2.nodes.EvalContext(environment, template_name=None)

Holds evaluation time information. Custom attributes can be attachedto it in extensions.
autoescape

True or False depending on if autoescaping is active or not.
volatile

True if the compiler cannot evaluate some expressions at compiletime. At runtime this should always be False.

Custom Tests¶

Tests work like filters just that there is no way for a test to get accessto the environment or context and that they can’t be chained. The returnvalue of a test should be True or False. The purpose of a test is togive the template designers the possibility to perform type and conformabilitychecks.

Here a simple test that checks if a variable is a prime number:

  1. import math
  2.  
  3. def is_prime(n):
  4. if n == 2:
  5. return True
  6. for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1):
  7. if n % i == 0:
  8. return False
  9. return True

You can register it on the template environment by updating thetests dict on the environment:

  1. environment.tests['prime'] = is_prime

A template designer can then use the test like this:

  1. {% if 42 is prime %}
  2. 42 is a prime number
  3. {% else %}
  4. 42 is not a prime number
  5. {% endif %}

The Global Namespace¶

Variables stored in the Environment.globals dict are special as theyare available for imported templates too, even if they are imported withoutcontext. This is the place where you can put variables and functionsthat should be available all the time. Additionally Template.globalsexist that are variables available to a specific template that are availableto all render() calls.

Low Level API¶

The low level API exposes functionality that can be useful to understand someimplementation details, debugging purposes or advanced extension techniques. Unless you know exactly what you are doing wedon’t recommend using any of those.

Environment.lex(source, name=None, filename=None)

Lex the given sourcecode and return a generator that yieldstokens as tuples in the form (lineno, tokentype, value).This can be useful for extension developmentand debugging templates.

This does not perform preprocessing. If you want the preprocessingof the extensions to be applied you have to filter source throughthe preprocess() method.
Environment.parse(_source, name=None, filename=None)

Parse the sourcecode and return the abstract syntax tree. Thistree of nodes is used by the compiler to convert the template intoexecutable source- or bytecode. This is useful for debugging or toextract information from templates.

If you are developing Jinja2 extensionsthis gives you a good overview of the node tree generated.
Environment.preprocess(source, name=None, filename=None)

Preprocesses the source with all extensions. This is automaticallycalled for all parsing and compiling methods but not for lex()because there you usually only want the actual source tokenized.
Template.newcontext(_vars=None, shared=False, locals=None)

Create a new Context for this template. The varsprovided will be passed to the template. Per default the globalsare added to the context. If shared is set to True the datais passed as it to the context without adding the globals.

locals can be a dict of local variables for internal usage.
Template.rootrender_func(_context)

This is the low level render function. It’s passed a Contextthat has to be created by new_context() of the same template ora compatible template. This render function is generated by thecompiler from the template code and returns a generator that yieldsunicode strings.

If an exception in the template code happens the template engine willnot rewrite the exception but pass through the original one. As amatter of fact this function should only be called from within arender() / generate() / stream() call.
Template.blocks

A dict of block render functions. Each of these functions works exactlylike the root_render_func() with the same limitations.
Template.isup_to_date

This attribute is _False
if there is a newer version of the templateavailable, otherwise True.

Note

The low-level API is fragile. Future Jinja2 versions will try not tochange it in a backwards incompatible way but modifications in the Jinja2core may shine through. For example if Jinja2 introduces a new AST nodein later versions that may be returned by parse().

The Meta API¶

New in version 2.2.

The meta API returns some information about abstract syntax trees thatcould help applications to implement more advanced template concepts. Allthe functions of the meta API operate on an abstract syntax tree asreturned by the Environment.parse() method.

jinja2.meta.findundeclared_variables(_ast)

Returns a set of all variables in the AST that will be looked up fromthe context at runtime. Because at compile time it’s not known whichvariables will be used depending on the path the execution takes atruntime, all variables are returned.



  1. >>> from jinja2 import Environment, meta
    >>> env = Environment()
    >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')
    >>> meta.findundeclared_variables(ast) == set(['bar'])
    True





Implementation

Internally the code generator is used for finding undeclared variables.This is good to know because the code generator might raise aTemplateAssertionError during compilation and as a matter offact this function can currently raise that exception as well.

jinja2.meta.find_referenced_templates(_ast)

Finds all the referenced templates from the AST. This will return aniterator over all the hardcoded template extensions, inclusions andimports. If dynamic inheritance or inclusion is used, None will beyielded.



  1. >>> from jinja2 import Environment, meta
    >>> env = Environment()
    >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')
    >>> list(meta.find_referenced_templates(ast))
    ['layout.html', None]




This function is useful for dependency tracking. For example if you wantto rebuild parts of the website after a layout template has changed.

原文:

http://jinja.pocoo.org/docs/2.10/api/