Toggle navigation


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


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 of Template class, an environment is created automatically for you, albeit a shared one.

Most applications will create one Environment object on application initialization and use that to load templates. In some cases however, it’s useful to have multiple environments side by side, if different configurations are in use.

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

from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
    loader=PackageLoader('yourapplication', 'templates'),
    autoescape=select_autoescape(['html', 'xml'])

This will create a template environment with the default settings and a loader that looks up the templates in the [UNKNOWN NODE title_reference] folder inside the [UNKNOWN NODE title_reference] python package. Different loaders are available and you can also write your own if you want to load templates from a database or other resources. This also enables autoescaping for HTML and XML files.

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

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

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

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

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


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

Python 2.x supports two ways of representing string objects. One is the [UNKNOWN NODE title_reference] type and the other is the [UNKNOWN NODE title_reference] type, both of which extend a type called [UNKNOWN NODE title_reference]. Unfortunately the default is [UNKNOWN NODE title_reference] which should not be used to store text based information unless only ASCII characters are used. With Python 2.6 it is possible to make [UNKNOWN NODE title_reference] the default on a per module level and with Python 3 it will be the default.

To explicitly use a Unicode string you have to prefix the string literal with a [UNKNOWN NODE title_reference]: u'Hänsel und Gretel sagen Hallo'. That way Python will store the string as Unicode by decoding the string with the character encoding from the current Python module. If no encoding is specified this defaults 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 or second line of the Python module using the Unicode literal:

# -*- coding: utf-8 -*-

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

It is not possible to use Jinja2 to process non-Unicode data. The reason for this is that Jinja2 uses Unicode already on the language level. For example Jinja2 treats the non-breaking space as valid whitespace inside expressions which requires knowledge of the encoding or operating on an Unicode string.

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

Another important thing is how Jinja2 is handling string literals in templates. A naive implementation would be using Unicode strings for all string literals but it turned out in the past that this is problematic as some libraries are typechecking against [UNKNOWN NODE title_reference] explicitly. For example [UNKNOWN NODE title_reference] does not accept Unicode arguments. To not break it completely Jinja2 is returning [UNKNOWN NODE title_reference] for strings that fit into ASCII and for everything else [UNKNOWN NODE title_reference]:

[UNKNOWN NODE doctest_block]

High Level API

The high-level API is the API you will use in the application to load and render Jinja2 templates. The Low Level API on the other side is only useful if you want to dig deeper into Jinja2 or develop extensions.

class jinja2.Environment([options])

The core component of Jinja is the [UNKNOWN NODE title_reference]. It contains important shared variables like configuration, filters, tests, globals and others. Instances of this class may be modified if they are not shared and if no template was loaded so far. Modifications on environments after the first template was loaded will lead to surprising effects and undefined behavior.

Here are the possible initialization parameters:

[UNKNOWN NODE title_reference]
The string marking the beginning of a block. Defaults to '{%'.
[UNKNOWN NODE title_reference]
The string marking the end of a block. Defaults to '%}'.
[UNKNOWN NODE title_reference]
The string marking the beginning of a print statement. Defaults to '{{'.
[UNKNOWN NODE title_reference]
The string marking the end of a print statement. Defaults to '}}'.
[UNKNOWN NODE title_reference]
The string marking the beginning of a comment. Defaults to '{#'.
[UNKNOWN NODE title_reference]
The string marking the end of a comment. Defaults to '#}'.
[UNKNOWN NODE title_reference]
If given and a string, this will be used as prefix for line based statements. See also Line Statements.
[UNKNOWN NODE title_reference]

If given and a string, this will be used as prefix for line based comments. See also Line Statements.

New in version 2.2.

[UNKNOWN NODE title_reference]
If this is set to True the first newline after a block is removed (block, not variable tag!). Defaults to [UNKNOWN NODE title_reference].
[UNKNOWN NODE title_reference]
If this is set to True leading spaces and tabs are stripped from the start of a line to a block. Defaults to [UNKNOWN NODE title_reference].
[UNKNOWN NODE title_reference]
The sequence that starts a newline. Must be one of '\r', '\n' or '\r\n'. The default is '\n' which is a useful default for Linux and OS X systems as well as web applications.
[UNKNOWN NODE title_reference]

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.

[UNKNOWN NODE title_reference]
List of Jinja extensions to use. This can either be import paths as strings or extension classes. For more information have a look at the extensions documentation.
[UNKNOWN NODE title_reference]
should the optimizer be enabled? Default is True.
[UNKNOWN NODE title_reference]
Undefined or a subclass of it that is used to represent undefined values in the template.
[UNKNOWN NODE title_reference]
A callable that can be used to process the result of a variable expression before it is output. For example one can convert None implicitly into an empty string here.
[UNKNOWN NODE title_reference]

If set to True the XML/HTML autoescaping feature is enabled by default. For more details about autoescaping see Markup. As of Jinja 2.4 this can also be a callable that is passed the template name and has to return True or False depending on autoescape should be enabled by default.

Changed in version 2.4: [UNKNOWN NODE title_reference] can now be a function

[UNKNOWN NODE title_reference]
The template loader for this environment.
[UNKNOWN NODE title_reference]

The size of the cache. Per default this is 400 which means that if more than 400 templates are loaded the loader will clean out the least recently used template. If the cache size is set to 0 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.

[UNKNOWN NODE title_reference]
Some loaders load templates from locations where the template sources may change (ie: file system or database). If auto_reload is set to True (default) every time a template is requested the loader checks if the source changed and if yes, it will reload the template. For higher performance it’s possible to disable that.
[UNKNOWN NODE title_reference]

If set to a bytecode cache object, this object will provide a cache for the internal Jinja bytecode so that templates don’t have to be parsed if they were not changed.

See Bytecode Cache for more information.

[UNKNOWN NODE title_reference]
If set to true this enables async template execution which allows you to take advantage of newer Python features. This requires Python 3.6 or later.

If a template was created by using the Template constructor an environment is created automatically. These environments are created as shared environments which means that multiple templates may have the same anonymous environment. For all shared environments this attribute is [UNKNOWN NODE title_reference], else [UNKNOWN NODE title_reference].


If the environment is sandboxed this attribute is [UNKNOWN NODE title_reference]. For the sandbox mode have a look at the documentation for the SandboxedEnvironment.


A dict of filters for this environment. As long as no template was loaded it’s safe to add new filters or remove old. For custom filters see Custom Filters. For valid filter names have a look at Notes on Identifiers.


A dict of test functions for this environment. As long as no template was loaded it’s safe to modify this dict. For custom tests see Custom Tests. For valid test names have a look at Notes on Identifiers.


A dict of global variables. These variables are always available in a template. As long as no template was loaded it’s safe to 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 to change the runtime behavior or certain template features. Usually these are security related.


The class used for code generation. This should not be changed in most cases, unless you need to modify the Python code a template compiles to.


The context used for templates. This should not be changed in most cases, unless you need to modify internals of how template variables are handled. For details, see Context.


Create a new overlay environment that shares all the data with the current environment except for cache and the overridden attributes. Extensions cannot be removed for an overlayed environment. An overlayed environment automatically gets all the extensions of the environment it is linked to plus optional extra extensions.

Creating overlays should happen after the initial environment was set up completely. Not all attributes are truly linked, some are just copied over so modifications on the original environment may not shine through.

undefined([hint, obj, name, exc])

Creates a new Undefined object for [UNKNOWN NODE title_reference]. This is useful for filters or functions that may return undefined objects for some operations. All parameters except of [UNKNOWN NODE title_reference] should be provided as keyword parameters for better readability. The [UNKNOWN NODE title_reference] is used as error message for the exception if provided, otherwise the error message will be generated from [UNKNOWN NODE title_reference] and [UNKNOWN NODE title_reference] automatically. The exception provided as [UNKNOWN NODE title_reference] is raised if something with the generated undefined object is done that the undefined object does not allow. The default exception is UndefinedError. If a [UNKNOWN NODE title_reference] is provided the [UNKNOWN NODE title_reference] may be omitted.

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

return environment.undefined(name='some_name')

This means that the name [UNKNOWN NODE title_reference] is not defined. If the name was from an attribute of an object it makes sense to tell the undefined 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 example the first() filter creates an undefined object that way:

return environment.undefined('no first item, sequence was empty')

If it the [UNKNOWN NODE title_reference] or [UNKNOWN NODE title_reference] is known (for example because an attribute was accessed) it should be passed to the undefined object, even if a custom [UNKNOWN NODE title_reference] is provided. This gives undefined objects the possibility to enhance the error message.


Adds an extension after the environment was created.

New in version 2.5.

compile_expression(source, undefined_to_none=True)

A handy helper method that returns a callable that accepts keyword arguments that appear as variables in the expression. If called it returns the result of the expression.

This is useful if applications want to use the same rules as Jinja in template “configuration files” or similar situations.

Example usage:

[UNKNOWN NODE doctest_block]

Per default the return value is converted to [UNKNOWN NODE title_reference] if the expression returns an undefined value. This can be changed by setting [UNKNOWN NODE title_reference] to [UNKNOWN NODE title_reference].

[UNKNOWN NODE doctest_block]

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 them and stores them in [UNKNOWN NODE title_reference]. If [UNKNOWN NODE title_reference] is [UNKNOWN NODE title_reference], instead of in a zipfile, the templates will be stored in a directory. By default a deflate zip algorithm is used. To switch to the stored algorithm, [UNKNOWN NODE title_reference] can be set to 'stored'.

[UNKNOWN NODE title_reference] and [UNKNOWN NODE title_reference] are passed to list_templates(). Each template returned will be compiled to the target folder or zipfile.

By default template compilation errors are ignored. In case a log function is provided, errors are logged. If you want template syntax errors to abort the compilation you can set [UNKNOWN NODE title_reference] to [UNKNOWN NODE title_reference] and you will get an exception on syntax errors.

If [UNKNOWN NODE title_reference] is set to [UNKNOWN NODE title_reference] .pyc files will be written to the target instead of standard .py files. This flag does not do anything on pypy and Python 3 where pyc files are not picked up by itself and don’t give much benefit.

New in version 2.4.


Add the items to the instance of the environment if they do not exist yet. This is used by extensions to register callbacks and configuration values without breaking inheritance.

from_string(source, globals=None, template_class=None)

Load a template from a string. This parses the source given and returns a Template object.

get_or_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 to get_template().

New in version 2.3.

get_template(name, parent=None, globals=None)

Load a template from the loader. If a loader is configured this method asks the loader for the template and returns a Template. If the [UNKNOWN NODE title_reference] parameter is not [UNKNOWN NODE title_reference], join_path() is called to get the real template name before loading.

The [UNKNOWN NODE title_reference] 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 is raised.

Changed in version 2.4: If [UNKNOWN NODE title_reference] is a Template object it is returned from the function unchanged.

join_path(template, parent)

Join a template with the parent. By default all the lookups are relative to the loader root so this method returns the [UNKNOWN NODE title_reference] parameter unchanged, but if the paths should be relative to the parent template, this function can be used to calculate the real template name.

Subclasses may override this method and implement template path joining here.

list_templates(extensions=None, filter_func=None)

Returns a list of templates for this environment. This requires that the loader supports the loader’s list_templates() method.

If there are other files in the template folder besides the actual templates, the returned list can be filtered. There are two ways: either [UNKNOWN NODE title_reference] is set to a list of file extensions for templates, or a [UNKNOWN NODE title_reference] can be provided which is a callable that is passed a template name and should return [UNKNOWN NODE title_reference] if it should end up in the result list.

If the loader does not support that, a TypeError is raised.

New in version 2.4.

select_template(names, parent=None, globals=None)

Works like get_template() but tries a number of templates before it fails. If it cannot find any of the templates, it will raise a TemplatesNotFound exception.

New in version 2.3.

Changed in version 2.4: If [UNKNOWN NODE title_reference] contains a Template object it is returned from the function unchanged.

class jinja2.Template

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 [UNKNOWN NODE title_reference] attribute that points to a temporary environment that is probably shared with other templates created with the constructor and compatible settings.

[UNKNOWN NODE doctest_block]

The dict with the globals of that template. It’s unsafe to modify this dict as it may be shared with other templates or the environment that loaded the template.


The loading name of the template. If the template was loaded from a string this is [UNKNOWN NODE title_reference].


The filename of the template on the file system if it was loaded from there. Otherwise this is [UNKNOWN NODE title_reference].


This method accepts the same arguments as the [UNKNOWN NODE title_reference] 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 unicode string.


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 unicode strings.

It accepts the same arguments as render().


Works exactly like generate() but returns a TemplateStream.


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')

An async version of generate(). Works very similarly but returns an async iterator instead.

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


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:

[UNKNOWN NODE doctest_block]

This attribute is not available if async mode is enabled.

class jinja2.environment.TemplateStream

A template stream works pretty much like an ordinary python generator but it can buffer multiple items to reduce the number of total iterations. Per default the output is unbuffered which means that for every unbuffered instruction in the template one unicode string is yielded.

If buffering is enabled with a buffer size of 5, five items are combined into a new unicode string. This is mainly useful if you are streaming big templates to a client via WSGI which flushes after each iteration.


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 encode before writing specify an [UNKNOWN NODE title_reference].

Example usage:

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

Enable buffering. Buffer [UNKNOWN NODE title_reference] items before yielding them.


Changed in version 2.4.

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

jinja2.select_autoescape(enabled_extensions=('html', 'htm', 'xml'), disabled_extensions=(), default_for_string=True, default=False)

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

If you want to enable it for all templates created from strings or for all templates with [UNKNOWN NODE title_reference] and [UNKNOWN NODE title_reference] extensions:

from jinja2 import Environment, select_autoescape
env = Environment(autoescape=select_autoescape(
    enabled_extensions=('html', 'xml'),

Example configuration to turn it on at all times except if the template ends with [UNKNOWN NODE title_reference]:

from jinja2 import Environment, select_autoescape
env = Environment(autoescape=select_autoescape(

The [UNKNOWN NODE title_reference] is an iterable of all the extensions that autoescaping should be enabled for. Likewise [UNKNOWN NODE title_reference] is a list of all templates it should be disabled for. If a template is loaded from a string then the default from [UNKNOWN NODE title_reference] is used. If nothing matches then the initial value of autoescaping is set to the value of [UNKNOWN NODE title_reference].

For security reasons this function operates case insensitive.

New in version 2.9.

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

from jinja2 import Environment, select_autoescape
env = Environment(autoescape=select_autoescape(['html', 'htm', 'xml']),

The select_autoescape() function returns a function that works roughly like this:

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 also accept [UNKNOWN NODE title_reference] as valid template name. This will be passed when generating templates from strings. You should always configure autoescaping as defaults in the future might change.

Inside the templates the behaviour can be temporarily changed by using the [UNKNOWN NODE title_reference] block (see Autoescape Overrides).

Notes on Identifiers

Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to match [a-zA-Z_][a-zA-Z0-9_]*. As a matter of fact non ASCII characters are currently not allowed. This limitation will probably go away as soon as unicode identifiers are fully specified for Python 3.

Filters and tests are looked up in separate namespaces and have slightly modified identifier syntax. Filters and tests may contain dots to group filters and tests by topic. For example it’s perfectly valid to add a function into the filter dict and call it [UNKNOWN NODE title_reference]. The regular expression 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 Environment constructor takes an [UNKNOWN NODE title_reference] parameter that can be one of those classes or a custom subclass of Undefined. Whenever the template engine is unable to look up a name or access an attribute one of those objects is created and returned. Some operations on undefined values are then allowed, others fail.

The closest to regular Python behavior is the [UNKNOWN NODE title_reference] which disallows all operations beside testing if it’s an undefined object.

class jinja2.Undefined

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

[UNKNOWN NODE doctest_block]

Either [UNKNOWN NODE title_reference] or an unicode string with the error message for the undefined object.


Either [UNKNOWN NODE title_reference] or the owner object that caused the undefined object to be created (for example because an attribute does not exist).


The name for the undefined variable / attribute or just [UNKNOWN NODE title_reference] if no such information exists.


The exception that the undefined object wants to raise. This is 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 generated from the undefined hints stored on the undefined object.

class jinja2.DebugUndefined

An undefined that returns the debug info when printed.

[UNKNOWN NODE doctest_block]
class jinja2.StrictUndefined

An undefined that barks on print and iteration as well as boolean tests and all kinds of comparisons. In other words: you can do nothing with it except checking if it’s defined using the [UNKNOWN NODE title_reference] test.

[UNKNOWN NODE doctest_block]

There is also a factory function that can decorate undefined objects to implement logging on failures:

jinja2.make_logging_undefined(logger=None, base=None)

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


logger = logging.getLogger(__name__)
LoggingUndefined = make_logging_undefined(

New in version 2.8.

  • logger – the logger to use. If not provided, a default logger is created.
  • base – the base class to add logging functionality to. This defaults to Undefined.

Undefined objects are created by calling undefined.

The Context

class jinja2.runtime.Context

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

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

The template context supports read only dict operations ([UNKNOWN NODE title_reference], [UNKNOWN NODE title_reference], [UNKNOWN NODE title_reference], [UNKNOWN NODE title_reference], [UNKNOWN NODE title_reference], [UNKNOWN NODE title_reference], [UNKNOWN NODE title_reference], [UNKNOWN NODE title_reference], [UNKNOWN NODE title_reference]). Additionally there is a resolve() method that doesn’t fail with a [UNKNOWN NODE title_reference] but returns an Undefined object for missing variables.


A dict of read only, global variables the template looks up. These can either come from another Context, from the Environment.globals or Template.globals or points to a dict created by combining the globals with the variables passed to the render function. It must not be altered.


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


The environment that loaded the template.


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


The load name of the template owning this context.


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


The current Evaluation Context.

call(callable, *args, **kwargs)

Call the callable with the arguments and keyword arguments provided but inject the active context or environment as first argument if the callable is a contextfunction() or environmentfunction().


Return the complete context as dict including the exported variables. For optimizations reasons this might not return an actual copy so be careful with using it.


Get a new dict with the exported variables.


Looks up a variable like [UNKNOWN NODE title_reference] or [UNKNOWN NODE title_reference] but returns an Undefined object with the name of the name looked up.


Loaders are responsible for loading templates from a resource such as the file system. The environment will keep the compiled modules in memory like Python’s [UNKNOWN NODE title_reference]. Unlike [UNKNOWN NODE title_reference] however this cache is limited in size by default and templates are automatically reloaded. All loaders are subclasses of BaseLoader. If you want to create your own loader, subclass BaseLoader and override [UNKNOWN NODE title_reference].

class jinja2.BaseLoader

Baseclass for all loaders. Subclass this and override [UNKNOWN NODE title_reference] to implement a custom loading mechanism. The environment provides a [UNKNOWN NODE title_reference] method that calls the loader’s [UNKNOWN NODE title_reference] method to get the Template object.

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

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

class MyLoader(BaseLoader):

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

    def get_source(self, environment, template):
        path = join(self.path, template)
        if not exists(path):
            raise TemplateNotFound(template)
        mtime = getmtime(path)
        with file(path) as f:
            source ='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 a tuple in the form (source, filename, uptodate) or raise a [UNKNOWN NODE title_reference] error if it can’t locate the template.

The source part of the returned tuple must be the source of the template as unicode string or a ASCII bytestring. The filename should be the name of the file on the filesystem if it was loaded from there, otherwise [UNKNOWN NODE title_reference]. The filename is used by python for the tracebacks if no loader extension is used.

The last item in the tuple is the [UNKNOWN NODE title_reference] function. If auto reloading is enabled it’s always called to check if the template changed. No arguments are passed so the function must store the old state somewhere (for example in a closure). If it returns [UNKNOWN NODE title_reference] the template will be reloaded.

load(environment, name, globals=None)

Loads a template. This method looks up the template in the cache or loads one by calling get_source(). Subclasses should not override this method as loaders working on collections of other loaders (such as PrefixLoader or ChoiceLoader) will not call this method but [UNKNOWN NODE title_reference] 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 templates in 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 multiple locations are wanted a list of them which is then looked up in the given order:

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

Per default the template encoding is 'utf-8' which can be changed by setting the [UNKNOWN NODE title_reference] parameter to something else.

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

>>> 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 with the name of the python package and the path to the templates in that package:

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 changed by setting the [UNKNOWN NODE title_reference] parameter to something else. Due to the nature of eggs it’s only possible to reload templates if the package was loaded from 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 unicode strings bound to template names. This loader is useful for unittesting:

[UNKNOWN NODE doctest_block]

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. The function receives the name of the template and has to return either an unicode string with the template source, a tuple in the form (source, filename, uptodatefunc) or [UNKNOWN NODE title_reference] if the template does not exist.

[UNKNOWN NODE doctest_block]

The [UNKNOWN NODE title_reference] is a function that is called if autoreload is enabled and has to return [UNKNOWN NODE title_reference] if the template is still up to date. For more details have a look at BaseLoader.get_source() which has the same return value.

class jinja2.PrefixLoader(mapping, delimiter='/')

A loader that is passed a dict of loaders where each loader is bound to a prefix. The prefix is delimited from the template by a slash per default, which can be changed by setting the [UNKNOWN NODE title_reference] argument to something else:

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 [UNKNOWN NODE title_reference] just that no prefix is specified. If a template could not be found by one loader the next one is tried.

[UNKNOWN NODE doctest_block]

This is useful if you want to allow users to override builtin templates from a different location.

class jinja2.ModuleLoader(path)

This loader loads templates from precompiled templates.

Example usage:

[UNKNOWN NODE doctest_block]

Templates can be precompiled with Environment.compile_templates().

Bytecode Cache

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

This is especially useful if you have a web application that is initialized on the first request and Jinja compiles many templates at once which slows down the 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 class and override load_bytecode() and dump_bytecode(). Both of these methods are passed a Bucket.

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

from os import path

class MyCache(BytecodeCache):

    def __init__(self, directory): = directory

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

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

A more advanced version of a filesystem based bytecode cache is part of Jinja2.


Clears the cache. This method is not used by Jinja2 but should be implemented to allow applications to clear the bytecode cache used by a particular environment.


Subclasses have to override this method to write the bytecode from a bucket back to the cache. If it unable to do so it must not fail silently but raise an exception.


Subclasses have to override this method to load bytecode into a bucket. If they are not able to find code in the cache for the bucket, it must not do anything.

class jinja2.bccache.Bucket(environment, key, checksum)

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

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


The Environment that created the bucket.


The unique cache key for this bucket


The bytecode if it’s loaded, otherwise [UNKNOWN NODE title_reference].


Load bytecode from a string.


Return the bytecode as string.


Loads bytecode from a file or file like object.


Resets the bucket (unloads the bytecode).


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 accepts two arguments: The directory where the cache items are stored and a pattern string that is used to build the filename.

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

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

[UNKNOWN NODE doctest_block]

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 for storing the information. It does not enforce a specific memcache library (tummy’s memcache or cmemcache) but will accept any class that provides the minimal interface required.

Libraries compatible with this class:

(Unfortunately the django cache interface is not compatible because it does not support storing binary data, only unicode. You can however pass the underlying cache client to the bytecode cache which is available as [UNKNOWN NODE title_reference].)

The minimal interface for the client passed to the constructor is this:

class MinimalClientInterface
set(key, value[, timeout])

Stores the bytecode in the cache. [UNKNOWN NODE title_reference] is a string and [UNKNOWN NODE title_reference] the timeout of the key. If timeout is not provided a default timeout or no timeout should be assumed, if it’s provided it’s an integer with the number of seconds the cache item should exist.


Returns the value for the cache key. If the item does not exist in the cache the return value must be [UNKNOWN NODE title_reference].

The other arguments to the constructor are the prefix for all keys that is added before the actual cache key and the timeout for the bytecode in the 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 the [UNKNOWN NODE title_reference] parameter.

Async Support

Starting with version 2.9, Jinja2 also supports the Python [UNKNOWN NODE title_reference] and [UNKNOWN NODE title_reference] constructs. As far as template designers go this feature is entirely opaque to them however as a developer you should be aware of how it’s implemented as it influences what type of APIs you can safely expose to the template environment.

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

  • template rendering will require an event loop to be set for the current thread (asyncio.get_event_loop needs to return one)
  • all template generation code internally runs async generators which means that you will pay a performance penalty even if the non sync methods are used!
  • The sync methods are based on async methods if the async mode is enabled which means that [UNKNOWN NODE title_reference] for instance will internally invoke [UNKNOWN NODE title_reference] and run it as part of the current event loop until the execution finished.

Awaitable objects can be returned from functions in templates and any function call in a template will automatically await the result. This means that you can let provide a method that asynchronously loads data from a database if you so desire and from the template designer’s point of view this is just another function they can call. This means that the await you would normally issue in Python is implied. However this only applies to function calls. If an attribute for instance would be an avaitable object then this would not result in the expected behavior.

Likewise iterations with a [UNKNOWN NODE title_reference] loop support async iterators.


Starting with Jinja 2.9 policies can be configured on the environment which can slightly influence how filters and other template constructs behave. They can be configured with the policies attribute.


env.policies['urlize.rel'] = 'nofollow noopener'
This boolean controls on Python 2 if Jinja2 should store ASCII only literals as bytestring instead of unicode strings. This used to be always enabled for Jinja versions below 2.9 and now can be changed. Traditionally it was done this way since some APIs in Python 2 failed badly 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 unicode internally.
Configures the leeway default for the [UNKNOWN NODE title_reference] filter. Leeway as introduced in 2.9 but to restore compatibility with older templates it can be configured to [UNKNOWN NODE title_reference] to get the old behavior back. The default is [UNKNOWN NODE title_reference].
A string that defines the items for the [UNKNOWN NODE title_reference] attribute of generated links with the [UNKNOWN NODE title_reference] filter. These items are always added. The default is [UNKNOWN NODE title_reference].
The default target that is issued for links from the [UNKNOWN NODE title_reference] filter if no other target is defined by the call explicitly.
If this is set to a value other than [UNKNOWN NODE title_reference] then the [UNKNOWN NODE title_reference] filter will dump with this function instead of the default one. Note that this function should accept arbitrary extra arguments which might be passed in the future from the filter. Currently the only argument that might be passed is [UNKNOWN NODE title_reference]. The default dump function is json.dumps.
Keyword arguments to be passed to the dump function. The default is {'sort_keys': True}.
If this is set to [UNKNOWN NODE title_reference], {% trans %} blocks of the i18n Extension will always unify linebreaks and surrounding whitespace as if the [UNKNOWN NODE title_reference] modifier was used.


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


Decorator for marking environment dependent filters. The current Environment is passed to the filter as first argument.


Decorator for marking context dependent filters. The current Context will be passed as first argument.


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

New in version 2.4.


This decorator can be used to mark a function or method as environment callable. This decorator works exactly like the contextfunction() decorator just that the first argument is the active Environment and not context.


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

def get_exported_names(context):
    return sorted(context.exported_vars)

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

New in version 2.4.


Convert the characters &, <, >, ', and " in string [UNKNOWN NODE title_reference] to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. This function will not escaped objects that do have an HTML representation such as already escaped data.

The return value is a Markup string.


Jinja2 keeps internal caches for environments and lexers. These are used so that Jinja2 doesn’t have to recreate environments and lexers all the time. Normally you don’t have to care about that but if you are measuring memory consumption you may want to clean the caches.


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

def default(var, default=''):
    if is_undefined(var):
        return default
    return var
class jinja2.Markup([string])

Marks a string as being safe for inclusion in HTML/XML output without needing to be escaped. This implements the [UNKNOWN NODE title_reference] interface a couple of frameworks and web applications use. Markup is a direct subclass of [UNKNOWN NODE title_reference] and provides all the methods of [UNKNOWN NODE title_reference] just that it escapes arguments passed and always returns [UNKNOWN NODE title_reference].

The [UNKNOWN NODE title_reference] function returns markup objects so that double escaping can’t happen.

The constructor of the Markup class can be used for three different things: When passed an unicode object it’s assumed to be safe, when passed an object with an HTML representation (has an [UNKNOWN NODE title_reference] method) that representation is used, otherwise the object passed is converted into a unicode string and then assumed to be safe:

[UNKNOWN NODE doctest_block]

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

[UNKNOWN NODE doctest_block]

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

[UNKNOWN NODE doctest_block]
classmethod escape(s)

Escape the string. Works like escape() with the difference that for subclasses of Markup this function would return the correct subclass.


Unescape markup into an text_type string and strip all tags. This also resolves known HTML4 and XHTML entities. Whitespace is normalized to one:

[UNKNOWN NODE doctest_block]

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

[UNKNOWN NODE doctest_block]


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 templates are selected. This is a subclass of TemplateNotFound exception, 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.


The error message as utf-8 bytestring.


The line number where the error occurred


The load name for the template as unicode string.


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

The reason why the filename and error message are bytestrings and not unicode strings is that Python 2.x is not using unicode for exceptions and 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 situations Jinja may raise this exception.

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

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

Custom Filters

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

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

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

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

environment.filters['datetimeformat'] = datetimeformat

Inside the template it can then be used as follows:

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

Filters can also be passed the current template context or environment. This is useful if a filter wants to return an undefined value or check the current autoescape setting. For this purpose three decorators exist: environmentfilter(), contextfilter() and evalcontextfilter().

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

import re
from jinja2 import evalcontextfilter, Markup, escape

_paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')

def nl2br(eval_ctx, value):
    result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', Markup('<br>\n'))
                          for p in _paragraph_re.split(escape(value)))
    if eval_ctx.autoescape:
        result = Markup(result)
    return result

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

Evaluation Context

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

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

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

Previous versions:

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 the evaluation context from the actual context, or use a evalcontextfilter() which directly passes the evaluation context to the function:

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

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. Modifications must only happen with a nodes.EvalContextModifier and nodes.ScopedEvalContextModifier from an extension, not on the eval context object itself.

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

Holds evaluation time information. Custom attributes can be attached to it in extensions.


[UNKNOWN NODE title_reference] or [UNKNOWN NODE title_reference] depending on if autoescaping is active or not.


[UNKNOWN NODE title_reference] if the compiler cannot evaluate some expressions at compile time. At runtime this should always be [UNKNOWN NODE title_reference].

Custom Tests

Tests work like filters just that there is no way for a test to get access to the environment or context and that they can’t be chained. The return value of a test should be [UNKNOWN NODE title_reference] or [UNKNOWN NODE title_reference]. The purpose of a test is to give the template designers the possibility to perform type and conformability checks.

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

import math

def is_prime(n):
    if n == 2:
        return True
    for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1):
        if n % i == 0:
            return False
    return True

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

environment.tests['prime'] = is_prime

A template designer can then use the test like this:

{% if 42 is prime %}
    42 is a prime number
{% else %}
    42 is not a prime number
{% endif %}

The Global Namespace

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

Low Level API

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

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

Lex the given sourcecode and return a generator that yields tokens as tuples in the form (lineno, token_type, value). This can be useful for extension development and debugging templates.

This does not perform preprocessing. If you want the preprocessing of the extensions to be applied you have to filter source through the preprocess() method.

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

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

If you are developing Jinja2 extensions this 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 automatically called for all parsing and compiling methods but not for lex() because there you usually only want the actual source tokenized.

Template.new_context(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 [UNKNOWN NODE title_reference] the data is passed as it to the context without adding the globals.

[UNKNOWN NODE title_reference] can be a dict of local variables for internal usage.


This is the low level render function. It’s passed a Context that has to be created by new_context() of the same template or a compatible template. This render function is generated by the compiler from the template code and returns a generator that yields unicode strings.

If an exception in the template code happens the template engine will not rewrite the exception but pass through the original one. As a matter of fact this function should only be called from within a render() / generate() / stream() call.


A dict of block render functions. Each of these functions works exactly like the root_render_func() with the same limitations.


This attribute is [UNKNOWN NODE title_reference] if there is a newer version of the template available, otherwise [UNKNOWN NODE title_reference].

The Meta API

New in version 2.2.

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


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

[UNKNOWN NODE doctest_block]

Finds all the referenced templates from the AST. This will return an iterator over all the hardcoded template extensions, inclusions and imports. If dynamic inheritance or inclusion is used, [UNKNOWN NODE title_reference] will be yielded.

[UNKNOWN NODE doctest_block]

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