Jinja Palletsprojects Com en 2.11.x PDF
Jinja Palletsprojects Com en 2.11.x PDF
Jinja Palletsprojects Com en 2.11.x PDF
x)
Release 2.11.1
Pallets
1 Introduction 3
1.1 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Basic API Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2 API 5
2.1 Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 Unicode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3 High Level API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.4 Autoescaping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.5 Notes on Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.6 Undefined Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.7 The Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.8 Loaders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.9 Bytecode Cache . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.10 Async Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.11 Policies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.12 Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.13 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.14 Custom Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.15 Evaluation Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.16 Custom Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.17 The Global Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.18 Low Level API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.19 The Meta API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3 Sandbox 31
3.1 API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.2 Operator Intercepting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
i
5.6 Whitespace Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
5.7 Escaping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
5.8 Line Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
5.9 Template Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
5.10 HTML Escaping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
5.11 List of Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
5.12 Import Context Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
5.13 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5.14 List of Builtin Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
5.15 List of Builtin Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
5.16 List of Global Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
5.17 Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
5.18 Autoescape Overrides . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
6 Extensions 75
6.1 Adding Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
6.2 i18n Extension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
6.3 Expression Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
6.4 Loop Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
6.5 With Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
6.6 Autoescape Extension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
6.7 Debug Extension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
6.8 Writing Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
6.9 Example Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
6.10 Extension API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
7 Integration 93
7.1 Babel Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
7.2 Pylons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
7.3 TextMate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
7.4 Vim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
11 Changelog 105
ii
11.1 2.11.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
11.2 Version 2.11.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
11.3 Version 2.11.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
11.4 Version 2.10.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
11.5 Version 2.10.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
11.6 Version 2.10.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
11.7 Version 2.10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
11.8 Version 2.9.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
11.9 Version 2.9.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
11.10 Version 2.9.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
11.11 Version 2.9.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
11.12 Version 2.9.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
11.13 Version 2.9.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
11.14 Version 2.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
11.15 Version 2.8.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
11.16 Version 2.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
11.17 Version 2.7.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
11.18 Version 2.7.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
11.19 Version 2.7.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
11.20 Version 2.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
11.21 Version 2.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
11.22 Version 2.5.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
11.23 Version 2.5.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
11.24 Version 2.5.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
11.25 Version 2.5.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
11.26 Version 2.5.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
11.27 Version 2.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
11.28 Version 2.4.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
11.29 Version 2.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
11.30 Version 2.3.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
11.31 Version 2.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
11.32 Version 2.2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
11.33 Version 2.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
11.34 Version 2.1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
11.35 Version 2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
11.36 Version 2.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
11.37 Version 2.0rc1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Index 121
iii
iv
Jinja Documentation (2.11.x), Release 2.11.1
Jinja is a modern and designer-friendly templating language for Python, modelled after Django’s templates. It is fast,
widely used and secure with the optional sandboxed template execution environment:
Features:
• sandboxed execution
• powerful automatic HTML escaping system for XSS prevention
• template inheritance
• compiles down to the optimal python code just in time
• optional ahead-of-time template compilation
• easy to debug. Line numbers of exceptions directly point to the correct line in the template.
• configurable syntax
CONTENTS: 1
Jinja Documentation (2.11.x), Release 2.11.1
2 CONTENTS:
CHAPTER
ONE
INTRODUCTION
This is the documentation for the Jinja general purpose templating language. Jinja is a library for Python that is
designed to be flexible, fast and secure.
If you have any exposure to other text-based template languages, such as Smarty or Django, you should feel right at
home with Jinja. It’s both designer and developer friendly by sticking to Python’s principles and adding functionality
useful for templating environments.
1.1 Prerequisites
Jinja works with Python 2.7.x and >= 3.5. If you are using Python 3.2 you can use an older release of Jinja (2.6) as
support for Python 3.2 was dropped in Jinja version 2.7. The last release which supported Python 2.6 and 3.3 was Jinja
2.10.
If you wish to use the PackageLoader class, you will also need setuptools or distribute installed at runtime.
1.2 Installation
You can install the most recent Jinja version using pip:
1. Install git
2. git clone git://github.com/pallets/jinja.git
3. cd jinja2
4. ln -s jinja2 /usr/lib/python2.X/site-packages
As an alternative to steps 4 you can also do python setup.py develop which will install the package via
distribute in development mode. This also has the advantage that the C extensions are compiled.
3
Jinja Documentation (2.11.x), Release 2.11.1
As of version 2.7 Jinja depends on the MarkupSafe module. If you install Jinja via pip it will be installed automati-
cally for you.
This section gives you a brief introduction to the Python API for Jinja templates.
The most basic way to create a template and render it is through Template. This however is not the recommended
way to work with it if your templates are not loaded from strings but the file system or another data source:
By creating an instance of Template you get back a new template object that provides a method called render()
which when called with a dict or keyword arguments expands the template. The dict or keywords arguments passed to
the template are the so-called “context” of the template.
What you can see here is that Jinja is using unicode internally and the return value is an unicode string. So make sure
that your application is indeed using unicode internally.
4 Chapter 1. Introduction
CHAPTER
TWO
API
This document describes the API to Jinja 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 Jinja templates.
2.1 Basics
Jinja 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 Jinja to load templates for your application looks roughly like this:
This will create a template environment with the default settings and a loader that looks up the templates in the
templates folder inside the yourapplication 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')
print(template.render(the='variables', go='here'))
Using a template loader rather than passing strings to Template or Environment.from_string() has multi-
ple advantages. Besides being a lot easier to use it also enables template inheritance.
Notes on Autoescaping
5
Jinja Documentation (2.11.x), Release 2.11.1
In future versions of Jinja we might enable autoescaping by default for security reasons. As such you are encouraged
to explicitly configure autoescaping now instead of relying on the default.
2.2 Unicode
Jinja 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 str type and the other is the unicode type, both
of which extend a type called basestring. Unfortunately the default is str 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 unicode 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 u: 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:
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 Jinja the default encoding of templates is
assumed to be utf-8.
It is not possible to use Jinja to process non-Unicode data. The reason for this is that Jinja uses Unicode already on the
language level. For example Jinja 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 Jinja 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 type-
checking against str explicitly. For example datetime.strftime does not accept Unicode arguments. To not break it
completely Jinja is returning str for strings that fit into ASCII and for everything else unicode:
The high-level API is the API you will use in the application to load and render Jinja templates. The Low Level API
on the other side is only useful if you want to dig deeper into Jinja or develop extensions.
class jinja2.Environment([options ])
The core component of Jinja is the Environment. 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
6 Chapter 2. API
Jinja Documentation (2.11.x), Release 2.11.1
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:
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 based statements. See
also Line Statements.
line_comment_prefix If given and a string, this will be used as prefix for line based comments. See
also Line Statements.
New in version 2.2.
trim_blocks If this is set to True the first newline after a block is removed (block, not variable tag!).
Defaults to False.
lstrip_blocks If this is set to True leading spaces and tabs are stripped from 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 a useful default for Linux and OS X systems as well as web
applications.
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 paths as strings or extension
classes. For more information have a look at the extensions documentation.
optimized should the optimizer be enabled? Default is True.
undefined Undefined or a subclass of it that is used to represent undefined values in the template.
finalize 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.
autoescape 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: 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 means that if more than 400 tem-
plates 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.
auto_reload 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.
bytecode_cache 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.
enable_async 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.
shared
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 True, else False.
sandboxed
If the environment is sandboxed this attribute is True. For the sandbox mode have a look at the documen-
tation for the SandboxedEnvironment.
filters
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.
tests
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.
globals
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.
policies
A dictionary with Policies. These can be reconfigured to change the runtime behavior or certain template
features. Usually these are security related.
code_generator_class
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.
context_class
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.
overlay([options ])
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 name. This is useful for filters or functions that may return unde-
fined objects for some operations. All parameters except of hint should be provided as keyword parameters
8 Chapter 2. API
Jinja Documentation (2.11.x), Release 2.11.1
for better readability. The hint is used as error message for the exception if provided, otherwise the er-
ror message will be generated from obj and name automatically. The exception provided as exc 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 hint is provided the name 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 some_name 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:
For a more complex example you can provide a hint. For example the first() filter creates an undefined
object that way:
If it the name or obj is known (for example because an attribute was accessed) it should be passed to the
undefined object, even if a custom hint is provided. This gives undefined objects the possibility to enhance
the error message.
add_extension(extension)
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:
Per default the return value is converted to None if the expression returns an undefined value. This can be
changed by setting undefined_to_none to False.
extensions and filter_func 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 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 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.
extend(**attributes)
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 parent parameter is not None, join_path() is called to 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 is raised.
Changed in version 2.4: If name 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 template 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 extensions is set to a list of file extensions for templates, or a filter_func can be
provided which is a callable that is passed a template name and should return True 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.
10 Chapter 2. API
Jinja Documentation (2.11.x), Release 2.11.1
globals
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.
name
The loading name of the template. If the template was loaded from a string this is None.
filename
The filename of the template on the file system if it was loaded from there. 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 arguments are given the context will be empty. These two calls do the same:
render_async([context ])
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:
generate_async([context ])
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.
property module
The template as module. This is used for imports in the template runtime but is also useful if one wants to
access exported template variables from the Python layer:
enable_buffering(size=5)
Enable buffering. Buffer size items before yielding them.
2.4 Autoescaping
12 Chapter 2. API
Jinja Documentation (2.11.x), Release 2.11.1
Example configuration to turn it on at all times except if the template ends with .txt:
The enabled_extensions is an iterable of all the extensions that autoescaping should be enabled for. Likewise
disabled_extensions is a list of all templates it should be disabled for. If a template is loaded from a string then
the default from default_for_string is used. If nothing matches then the initial value of autoescaping is set to the
value of default.
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:
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 None 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 autoescape block (see Autoescape Over-
rides).
Jinja uses Python naming rules. Valid identifiers can be any combination of Unicode characters accepted by Python.
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 to.unicode. The regular expression for filter and test identifiers is [a-zA-Z_][a-zA-Z0-9_]*(\.
[a-zA-Z_][a-zA-Z0-9_]*)*`.
These classes can be used as undefined types. The Environment constructor takes an undefined 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 StrictUndefined 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 UndefinedError:
>>> 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 for the undefined object.
_undefined_obj
Either None or the owner object that caused the undefined object to 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. 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.ChainableUndefined
An undefined that is chainable, where both __getattr__ and __getitem__ return itself rather than raising
an UndefinedError.
>>> foo = ChainableUndefined(name='foo')
>>> str(foo.bar['baz'])
''
>>> foo.bar['baz'] + 42
Traceback (most recent call last):
...
jinja2.exceptions.UndefinedError: 'foo' is undefined
14 Chapter 2. API
Jinja Documentation (2.11.x), Release 2.11.1
class jinja2.DebugUndefined
An undefined that returns the debug info when printed.
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 defined test.
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.
Example:
logger = logging.getLogger(__name__)
LoggingUndefined = make_logging_undefined(
logger=logger,
base=Undefined
)
Implementation
Undefined objects are implemented by overriding the special __underscore__ methods. For example the default
Undefined class implements __unicode__ in a way that it returns an empty string, however __int__ and others still
fail with an exception. To allow conversion to int by returning 0 you can implement your own:
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 common idiom
in undefined objects there is the helper method _fail_with_undefined_error() that does the error raising
automatically. Here a class that works like the regular Undefined but chokes on iteration:
class NonIterableUndefined(Undefined):
__iter__ = Undefined._fail_with_undefined_error
16 Chapter 2. API
Jinja Documentation (2.11.x), Release 2.11.1
Implementation
Context is immutable for the same reason Python’s frame locals are immutable inside functions. Both Jinja and Python
are not using the context / frame locals as data storage for variables but only as primary data source.
When a template accesses a variable the template does not define, Jinja looks up the variable in the context, after that
the variable is treated as if it was defined in the template.
2.8 Loaders
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 sys.modules. Unlike sys.modules 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 get_source.
class jinja2.BaseLoader
Baseclass for all loaders. Subclass this and override get_source to implement a custom loading mechanism. The
environment provides a get_template method that calls the loader’s load 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:
class MyLoader(BaseLoader):
get_source(environment, template)
Get the template source, filename and reload helper for a template. It’s passed the environment and tem-
2.8. Loaders 17
Jinja Documentation (2.11.x), Release 2.11.1
plate name and has to return a tuple in the form (source, filename, uptodate) or raise a Tem-
plateNotFound 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 None. The filename is used by python for the tracebacks if no loader extension is used.
The last item in the tuple is the uptodate 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 False 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 get_source directly.
Here a list of the builtin loaders Jinja 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:
Per default the template encoding is 'utf-8' which can be changed by setting the encoding parameter to
something else.
To follow symbolic links, set the followlinks parameter to True:
Only packages installed as directories (standard pip behavior) or zip/egg files (less common) are supported. The
Python API for introspecting data in packages is too limited to support other installation methods the way this
loader requires.
There is limited support for PEP 420 namespace packages. The template directory is assumed to only be in one
namespace contributor. Zip files contributing to a namespace are not supported.
Changed in version 2.11.0: No longer uses setuptools as a dependency.
Changed in version 2.11.0: Limited PEP 420 namespace package support.
18 Chapter 2. API
Jinja Documentation (2.11.x), Release 2.11.1
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:
The uptodatefunc is a function that is called if autoreload is enabled and has to return True 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 delimiter 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 PrefixLoader just that no prefix is specified. If a template could not be found by one
loader the next one is tried.
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:
2.8. Loaders 19
Jinja Documentation (2.11.x), Release 2.11.1
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:
class MyCache(BytecodeCache):
20 Chapter 2. API
Jinja Documentation (2.11.x), Release 2.11.1
code
The bytecode if it’s loaded, otherwise None.
bytecode_from_string(string)
Load bytecode from a string.
bytecode_to_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).
write_bytecode(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 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.
This bytecode cache supports clearing of the cache using the clear method.
class jinja2.MemcachedBytecodeCache(client, prefix=’jinja2/bytecode/’, timeout=None, ig-
nore_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:
• cachelib
• python-memcached
(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
django.core.cache.cache._client.)
The minimal interface for the client passed to the constructor is this:
class MinimalClientInterface
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 ignore_memcache_errors param-
eter.
2.11 Policies
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.
Example:
compiler.ascii_str: This boolean controls on Python 2 if Jinja 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.
truncate.leeway: Configures the leeway default for the truncate filter. Leeway as introduced in 2.9 but to restore
compatibility with older templates it can be configured to 0 to get the old behavior back. The default is 5.
urlize.rel: A string that defines the items for the rel attribute of generated links with the urlize filter. These items
are always added. The default is noopener.
22 Chapter 2. API
Jinja Documentation (2.11.x), Release 2.11.1
urlize.target: The default target that is issued for links from the urlize filter if no other target is defined by the
call explicitly.
json.dumps_function: If this is set to a value other than None then the tojson 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 indent. The default dump
function is json.dumps.
json.dumps_kwargs: 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 the i18n Extension will always unify line-
breaks and surrounding whitespace as if the trimmed modifier was used.
2.12 Utilities
These helper functions and classes are useful if you add custom filters or functions to a Jinja environment.
jinja2.environmentfilter(f )
Decorator for marking environment dependent filters. The current Environment is passed to the filter as first
argument.
jinja2.contextfilter(f )
Decorator for marking context dependent filters. The current Context will be passed as first argument.
jinja2.evalcontextfilter(f )
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.
jinja2.environmentfunction(f )
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.
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 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:
@contextfunction
def get_exported_names(context):
return sorted(context.exported_vars)
jinja2.evalcontextfunction(f )
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.
jinja2.escape(s)
Convert the characters &, <, >, ', and " in string s 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.
2.12. Utilities 23
Jinja Documentation (2.11.x), Release 2.11.1
jinja2.clear_caches()
Jinja keeps internal caches for environments and lexers. These are used so that Jinja 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.
jinja2.is_undefined(obj)
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 ])
A string that is ready to be safely inserted into an HTML or XML document, either because it was escaped or
because it was marked safe.
Passing an object to the constructor converts it to text and wraps it to mark it safe without escaping. To escape
the text, use the escape() class method instead.
>>> Markup('Hello, <em>World</em>!')
Markup('Hello, <em>World</em>!')
>>> Markup(42)
Markup('42')
>>> Markup.escape('Hello, <em>World</em>!')
Markup('Hello <em>World</em>!')
This implements the __html__() interface that some frameworks use. Passing an object that implements
__html__() will wrap the output of that method, marking it safe.
>>> class Foo:
... def __html__(self):
... return '<a href="/foo">foo</a>'
...
>>> Markup(Foo())
Markup('<a href="/foo">foo</a>')
This is a subclass of the text type (str in Python 3, unicode in Python 2). It has the same methods as that
type, but all methods escape their arguments and return a Markup instance.
>>> Markup('<em>%s</em>') % 'foo & bar'
Markup('<em>foo & bar</em>')
>>> Markup('<em>Hello</em> ') + '<foo>'
Markup('<em>Hello</em> <foo>')
classmethod escape(s)
Escape a string. Calls escape() and ensures that for subclasses the correct type is returned.
striptags()
unescape() the markup, remove tags, and normalize whitespace to single spaces.
>>> Markup('Main » <em>About</em>').striptags()
'Main » About'
unescape()
Convert escaped markup back into a text string. This replaces HTML entities with the characters they
represent.
24 Chapter 2. API
Jinja Documentation (2.11.x), Release 2.11.1
Note
The Jinja Markup class is compatible with at least Pylons and Genshi. It’s expected that more template engines and
framework will pick up the __html__ concept soon.
2.13 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.
Changed in version 2.11: If the given name is Undefined and no message was provided, an
UndefinedError is raised.
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.
Changed in version 2.11: If a name in the list of names is Undefined, a message about it being undefined is
shown rather than the empty string.
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 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.
2.13. Exceptions 25
Jinja Documentation (2.11.x), Release 2.11.1
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:
You can register it on the template environment by updating the filters dict on the environment:
environment.filters['datetimeformat'] = datetimeformat
Filters can also be passed the current template context or environment. This is useful if a filter wants to re-
turn 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)|\n){2,}')
@evalcontextfilter
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.
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 au-
toescape status from the environment. In new versions it’s encouraged to check the setting from the evaluation context
instead.
Previous versions:
26 Chapter 2. API
Jinja Documentation (2.11.x), Release 2.11.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 the evaluation context from the actual context,
or use a evalcontextfilter() which directly passes the evaluation context to the function:
@contextfilter
def filter(context, value):
result = do_something(value)
if context.eval_ctx.autoescape:
result = Markup(result)
return result
@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. 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.
autoescape
True or False depending on if autoescaping is active or not.
volatile
True if the compiler cannot evaluate some expressions at compile time. At runtime this should always be
False.
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 True or False. 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 range(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
{% if 42 is prime %}
42 is a prime number
{% else %}
42 is not a prime number
{% endif %}
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.
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 Jinja 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 True the data is passed as is to the context without adding the
globals.
locals can be a dict of local variables for internal usage.
Template.root_render_func(context)
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.
28 Chapter 2. API
Jinja Documentation (2.11.x), Release 2.11.1
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.
Template.blocks
A dict of block render functions. Each of these functions works exactly like the root_render_func() with
the same limitations.
Template.is_up_to_date
This attribute is False if there is a newer version of the template available, otherwise True.
Note
The low-level API is fragile. Future Jinja versions will try not to change it in a backwards incompatible way but
modifications in the Jinja core may shine through. For example if Jinja introduces a new AST node in later versions
that may be returned by parse().
Implementation
Internally the code generator is used for finding undeclared variables. This is good to know because the code
generator might raise a TemplateAssertionError during compilation and as a matter of fact 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 an iterator over all the hardcoded template
extensions, inclusions and imports. If dynamic inheritance or inclusion is used, None will be yielded.
>>> 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 want to rebuild parts of the website after a
layout template has changed.
30 Chapter 2. API
CHAPTER
THREE
SANDBOX
The Jinja sandbox can be used to evaluate untrusted code. Access to unsafe attributes and methods is prohibited.
Assuming env is a SandboxedEnvironment in the default configuration the following piece of code shows how
it works:
3.1 API
class jinja2.sandbox.SandboxedEnvironment([options ])
The sandboxed environment. It works like the regular environment but tells the compiler to generate sandboxed
code. Additionally subclasses of this environment may override the methods that tell the runtime what attributes
or functions are safe to access.
If the template tries to access insecure code a SecurityError is raised. However also other exceptions may
occur during the rendering so the caller has to ensure that all exceptions are caught.
call_binop(context, operator, left, right)
For intercepted binary operator calls (intercepted_binops()) this function is executed instead of
the builtin operator. This can be used to fine tune the behavior of certain operators.
New in version 2.6.
call_unop(context, operator, arg)
For intercepted unary operator calls (intercepted_unops()) this function is executed instead of the
builtin operator. This can be used to fine tune the behavior of certain operators.
New in version 2.6.
default_binop_table = {'%': <built-in function mod>, '*': <built-in function mul>, '*
default callback table for the binary operators. A copy of this is available on each instance of a sandboxed
environment as binop_table
default_unop_table = {'+': <built-in function pos>, '-': <built-in function neg>}
default callback table for the unary operators. A copy of this is available on each instance of a sandboxed
environment as unop_table
intercepted_binops = frozenset({})
a set of binary operators that should be intercepted. Each operator that is added to this set (empty by
31
Jinja Documentation (2.11.x), Release 2.11.1
default) is delegated to the call_binop() method that will perform the operator. The default operator
callback is specified by binop_table.
The following binary operators are interceptable: //, %, +, *, -, /, and **
The default operation form the operator table corresponds to the builtin function. Intercepted calls are
always slower than the native operator call, so make sure only to intercept the ones you are interested in.
New in version 2.6.
intercepted_unops = frozenset({})
a set of unary operators that should be intercepted. Each operator that is added to this set (empty by default)
is delegated to the call_unop() method that will perform the operator. The default operator callback
is specified by unop_table.
The following unary operators are interceptable: +, -
The default operation form the operator table corresponds to the builtin function. Intercepted calls are
always slower than the native operator call, so make sure only to intercept the ones you are interested in.
New in version 2.6.
is_safe_attribute(obj, attr, value)
The sandboxed environment will call this method to check if the attribute of an object is safe to access.
Per default all attributes starting with an underscore are considered private as well as the special attributes
of internal python objects as returned by the is_internal_attribute() function.
is_safe_callable(obj)
Check if an object is safely callable. Per default a function is considered safe unless the unsafe_callable
attribute exists and is True. Override this method to alter the behavior, but this won’t affect the unsafe
decorator from this module.
class jinja2.sandbox.ImmutableSandboxedEnvironment([options ])
Works exactly like the regular SandboxedEnvironment but does not permit modifications on the builtin mutable
objects list, set, and dict by using the modifies_known_mutable() function.
exception jinja2.sandbox.SecurityError(message=None)
Raised if a template tries to do something insecure if the sandbox is enabled.
jinja2.sandbox.unsafe(f )
Marks a function or method as unsafe.
@unsafe
def delete(self):
pass
jinja2.sandbox.is_internal_attribute(obj, attr)
Test if the attribute given is an internal python attribute. For example this function returns True for the func_code
attribute of python objects. This is useful if the environment method is_safe_attribute() is overridden.
jinja2.sandbox.modifies_known_mutable(obj, attr)
This function checks if an attribute on a builtin mutable object (list, dict, set or deque) would modify it if called.
It also supports the “user”-versions of the objects (sets.Set, UserDict.* etc.) and with Python 2.6 onwards the
abstract base classes MutableSet, MutableMapping, and MutableSequence.
32 Chapter 3. Sandbox
Jinja Documentation (2.11.x), Release 2.11.1
Note
The Jinja sandbox alone is no solution for perfect security. Especially for web applications you have to keep in mind
that users may create templates with arbitrary HTML in so it’s crucial to ensure that (if you are running multiple users
on the same server) they can’t harm each other via JavaScript insertions and much more.
Also the sandbox is only as good as the configuration. We strongly recommend only passing non-shared resources to
the template and use some sort of whitelisting for attributes.
Also keep in mind that templates may raise runtime or compile time errors, so make sure to catch them.
class MyEnvironment(SandboxedEnvironment):
intercepted_binops = frozenset(['**'])
Make sure to always call into the super method, even if you are not intercepting the call. Jinja might internally call the
method to evaluate expressions.
34 Chapter 3. Sandbox
CHAPTER
FOUR
The default Environment renders templates to strings. With NativeEnvironment, rendering a template pro-
duces a native Python type. This is useful if you are using Jinja outside the context of creating text files. For example,
your code may have an intermediate step where users may use templates to define values that will then be passed to a
traditional string environment.
4.1 Examples
>>> t = env.from_string('[{% for item in data %}{{ item + 1 }},{% endfor %}]')
>>> result = t.render(data=range(5))
>>> print(result)
[1, 2, 3, 4, 5]
>>> print(type(result))
list
Rendering something that doesn’t look like a Python literal produces a string:
Rendering a Python object produces that object as long as it is the only node:
35
Jinja Documentation (2.11.x), Release 2.11.1
4.2 API
class jinja2.nativetypes.NativeEnvironment([options ])
An environment that renders templates to native Python types.
class jinja2.nativetypes.NativeTemplate([options ])
render(*args, **kwargs)
Render the template to produce a native Python type. If the result is a single node, its value is returned. Oth-
erwise, the nodes are concatenated as strings. If the result can be parsed with ast.literal_eval(),
the parsed value is returned. Otherwise, the string is returned.
FIVE
This document describes the syntax and semantics of the template engine and will be most useful as reference to those
creating Jinja templates. As the template engine is very flexible, the configuration from the application can be slightly
different from the code presented here in terms of delimiters and behavior of undefined values.
5.1 Synopsis
A Jinja template is simply a text file. Jinja can generate any text-based format (HTML, XML, CSV, LaTeX, etc.). A
Jinja template doesn’t need to have a specific extension: .html, .xml, or any other extension is just fine.
A template contains variables and/or expressions, which get replaced with values when a template is rendered; and
tags, which control the logic of the template. The template syntax is heavily inspired by Django and Python.
Below is a minimal template that illustrates a few basics using the default Jinja configuration. We will cover the details
later in this document:
<!DOCTYPE html>
<html lang="en">
<head>
<title>My Webpage</title>
</head>
<body>
<ul id="navigation">
{% for item in navigation %}
<li><a href="{{ item.href }}">{{ item.caption }}</a></li>
{% endfor %}
</ul>
<h1>My Webpage</h1>
{{ a_variable }}
{# a comment #}
</body>
</html>
The following example shows the default configuration settings. An application developer can change the syntax
configuration from {% foo %} to <% foo %>, or something similar.
There are a few kinds of delimiters. The default Jinja delimiters are configured as follows:
• {% ... %} for Statements
• {{ ... }} for Expressions to print to the template output
• {# ... #} for Comments not included in the template output
37
Jinja Documentation (2.11.x), Release 2.11.1
As stated above, any file can be loaded as a template, regardless of file extension. Adding a .jinja extension,
like user.html.jinja may make it easier for some IDEs or editor plugins, but is not required. Autoescaping,
introduced later, can be applied based on file extension, so you’ll need to take the extra suffix into account in that case.
Another good heuristic for identifying templates is that they are in a templates folder, regardless of extension. This
is a common layout for projects.
5.2 Variables
Template variables are defined by the context dictionary passed to the template.
You can mess around with the variables in templates provided they are passed in by the application. Variables may have
attributes or elements on them you can access too. What attributes a variable has depends heavily on the application
providing that variable.
You can use a dot (.) to access attributes of a variable in addition to the standard Python __getitem__ “subscript”
syntax ([]).
The following lines do the same thing:
{{ foo.bar }}
{{ foo['bar'] }}
It’s important to know that the outer double-curly braces are not part of the variable, but the print statement. If you
access variables inside tags don’t put the braces around them.
If a variable or attribute does not exist, you will get back an undefined value. What you can do with that kind of value
depends on the application configuration: the default behavior is to evaluate to an empty string if printed or iterated
over, and to fail for every other operation.
Implementation
For the sake of convenience, foo.bar in Jinja does the following things on the Python layer:
• check for an attribute called bar on foo (getattr(foo, 'bar'))
• if there is not, check for an item 'bar' in foo (foo.__getitem__('bar'))
• if there is not, return an undefined object.
foo['bar'] works mostly the same with a small difference in sequence:
• check for an item 'bar' in foo. (foo.__getitem__('bar'))
• if there is not, check for an attribute called bar on foo. (getattr(foo, 'bar'))
• if there is not, return an undefined object.
This is important if an object has an item and attribute with the same name. Additionally, the attr() filter only looks
up attributes.
5.3 Filters
Variables can be modified by filters. Filters are separated from the variable by a pipe symbol (|) and may have
optional arguments in parentheses. Multiple filters can be chained. The output of one filter is applied to the next.
For example, {{ name|striptags|title }} will remove all HTML Tags from variable name and title-case
the output (title(striptags(name))).
Filters that accept arguments have parentheses around the arguments, just like a function call. For example: {{
listx|join(', ') }} will join a list with commas (str.join(', ', listx)).
The List of Builtin Filters below describes all the builtin filters.
5.4 Tests
Beside filters, there are also so-called “tests” available. Tests can be used to test a variable against a common expres-
sion. To test a variable or expression, you add is plus the name of the test after the variable. For example, to find out
if a variable is defined, you can do name is defined, which will then return true or false depending on whether
name is defined in the current template context.
Tests can accept arguments, too. If the test only takes one argument, you can leave out the parentheses. For example,
the following two expressions do the same thing:
{% if loop.index is divisibleby 3 %}
{% if loop.index is divisibleby(3) %}
The List of Builtin Tests below describes all the builtin tests.
5.5 Comments
To comment-out part of a line in a template, use the comment syntax which is by default set to {# ... #}. This
is useful to comment out parts of the template for debugging or to add information for other template designers or
yourself:
5.3. Filters 39
Jinja Documentation (2.11.x), Release 2.11.1
With both trim_blocks and lstrip_blocks enabled, you can put block tags on their own lines, and the entire block line
will be removed when rendered, preserving the whitespace of the contents. For example, without the trim_blocks and
lstrip_blocks options, this template:
<div>
{% if True %}
yay
{% endif %}
</div>
<div>
yay
</div>
But with both trim_blocks and lstrip_blocks enabled, the template block lines are removed and other whitespace is
preserved:
<div>
yay
</div>
You can manually disable the lstrip_blocks behavior by putting a plus sign (+) at the start of a block:
<div>
{%+ if something %}yay{% endif %}
</div>
You can also strip whitespace in templates by hand. If you add a minus sign (-) to the start or end of a block (e.g. a
For tag), a comment, or a variable expression, the whitespaces before or after that block will be removed:
This will yield all elements without whitespace between them. If seq was a list of numbers from 1 to 9, the output
would be 123456789.
If Line Statements are enabled, they strip leading whitespace automatically up to the beginning of the line.
By default, Jinja also removes trailing newlines. To keep single trailing newlines, configure Jinja to
keep_trailing_newline.
Note
You must not add whitespace between the tag and the minus sign.
valid:
invalid:
5.7 Escaping
It is sometimes desirable – even necessary – to have Jinja ignore parts it would otherwise handle as variables or blocks.
For example, if, with the default syntax, you want to use {{ as a raw string in a template and not start a variable, you
have to use a trick.
The easiest way to output a literal variable delimiter ({{) is by using a variable expression:
{{ '{{' }}
For bigger sections, it makes sense to mark a block raw. For example, to include example Jinja syntax in a template,
you can use this snippet:
{% raw %}
<ul>
{% for item in seq %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% endraw %}
Note
Minus sign at the end of {% raw -%} tag cleans all the spaces and newlines preceding the first character of your
raw data.
If line statements are enabled by the application, it’s possible to mark a line as a statement. For example, if the line
statement prefix is configured to #, the following two examples are equivalent:
<ul>
# for item in seq
<li>{{ item }}</li>
# endfor
</ul>
<ul>
{% for item in seq %}
<li>{{ item }}</li>
{% endfor %}
</ul>
The line statement prefix can appear anywhere on the line as long as no text precedes it. For better readability,
statements that start a block (such as for, if, elif etc.) may end with a colon:
Note
Line statements can span multiple lines if there are open parentheses, braces or brackets:
5.7. Escaping 41
Jinja Documentation (2.11.x), Release 2.11.1
<ul>
# for href, caption in [('index.html', 'Index'),
('about.html', 'About')]:
<li><a href="{{ href }}">{{ caption }}</a></li>
# endfor
</ul>
Since Jinja 2.2, line-based comments are available as well. For example, if the line-comment prefix is configured to
be ##, everything from ## to the end of the line is ignored (excluding the newline sign):
The most powerful part of Jinja is template inheritance. Template inheritance allows you to build a base “skeleton”
template that contains all the common elements of your site and defines blocks that child templates can override.
Sounds complicated but is very basic. It’s easiest to understand it by starting with an example.
This template, which we’ll call base.html, defines a simple HTML skeleton document that you might use for a
simple two-column page. It’s the job of “child” templates to fill the empty blocks with content:
<!DOCTYPE html>
<html lang="en">
<head>
{% block head %}
<link rel="stylesheet" href="style.css" />
<title>{% block title %}{% endblock %} - My Webpage</title>
{% endblock %}
</head>
<body>
<div id="content">{% block content %}{% endblock %}</div>
<div id="footer">
{% block footer %}
© Copyright 2008 by <a href="http://domain.invalid/">you</a>.
{% endblock %}
</div>
</body>
</html>
In this example, the {% block %} tags define four blocks that child templates can fill in. All the block tag does is
tell the template engine that a child template may override those placeholders in the template.
block tags can be inside other blocks such as if, but they will always be executed regardless of if the if block is
actually rendered.
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
{{ super() }}
<style type="text/css">
.important { color: #336699; }
</style>
{% endblock %}
{% block content %}
<h1>Index</h1>
<p class="important">
Welcome to my awesome homepage.
</p>
{% endblock %}
The {% extends %} tag is the key here. It tells the template engine that this template “extends” another template.
When the template system evaluates this template, it first locates the parent. The extends tag should be the first tag in
the template. Everything before it is printed out normally and may cause confusion. For details about this behavior
and how to take advantage of it, see Null-Master Fallback. Also a block will always be filled in regardless of whether
the surrounding condition is evaluated to be true or false.
The filename of the template depends on the template loader. For example, the FileSystemLoader allows you to
access other templates by giving the filename. You can access templates in subdirectories with a slash:
{% extends "layout/default.html" %}
But this behavior can depend on the application embedding Jinja. Note that since the child template doesn’t define the
footer block, the value from the parent template is used instead.
You can’t define multiple {% block %} tags with the same name in the same template. This limitation exists
because a block tag works in “both” directions. That is, a block tag doesn’t just provide a placeholder to fill - it also
defines the content that fills the placeholder in the parent. If there were two similarly-named {% block %} tags in
a template, that template’s parent wouldn’t know which one of the blocks’ content to use.
If you want to print a block multiple times, you can, however, use the special self variable and call the block with that
name:
It’s possible to render the contents of the parent block by calling super(). This gives back the results of the parent
block:
{% block sidebar %}
<h3>Table Of Contents</h3>
...
{{ super() }}
{% endblock %}
In the case of multiple levels of {% extends %}, super references may be chained (as in super.super()) to
skip levels in the inheritance tree.
For example:
# parent.tmpl
body: {% block body %}Hi from parent.{% endblock %}
# child.tmpl
{% extends "parent.tmpl" %}
{% block body %}Hi from child. {{ super() }}{% endblock %}
# grandchild1.tmpl
{% extends "child.tmpl" %}
{% block body %}Hi from grandchild1.{% endblock %}
# grandchild2.tmpl
{% extends "child.tmpl" %}
{% block body %}Hi from grandchild2. {{ super.super() }} {% endblock %}
Jinja allows you to put the name of the block after the end tag for better readability:
{% block sidebar %}
{% block inner_sidebar %}
...
{% endblock inner_sidebar %}
{% endblock sidebar %}
However, the name after the endblock word must match the block name.
Blocks can be nested for more complex layouts. However, per default blocks may not access variables from outer
scopes:
This example would output empty <li> items because item is unavailable inside the block. The reason for this is that
if the block is replaced by a child template, a variable would appear that was not defined in the block or passed to the
context.
Starting with Jinja 2.2, you can explicitly specify that variables are available in a block by setting the block to “scoped”
by adding the scoped modifier to a block declaration:
When overriding a block, the scoped modifier does not have to be provided.
{% extends layout_template %}
Previously, the layout_template variable had to be a string with the layout template’s filename for this to work.
When generating HTML from templates, there’s always a risk that a variable will include characters that affect the
resulting HTML. There are two approaches:
a. manually escaping each variable; or
b. automatically escaping everything by default.
Jinja supports both. What is used depends on the application configuration. The default configuration is no automatic
escaping; for various reasons:
• Escaping everything except for safe values will also mean that Jinja is escaping variables known to not include
HTML (e.g. numbers, booleans) which can be a huge performance hit.
• The information about the safety of a variable is very fragile. It could happen that by coercing safe and unsafe
values, the return value is double-escaped HTML.
If manual escaping is enabled, it’s your responsibility to escape variables if needed. What to escape? If you have
a variable that may include any of the following chars (>, <, &, or ") you SHOULD escape it unless the variable
contains well-formed and trusted HTML. Escaping works by piping the variable through the |e filter:
{{ user.username|e }}
When automatic escaping is enabled, everything is escaped by default except for values explicitly marked as safe.
Variables and expressions can be marked as safe either in:
a. The context dictionary by the application with markupsafe.Markup
b. The template, with the |safe filter.
If a string that you marked safe is passed through other Python code that doesn’t understand that mark, it may get lost.
Be aware of when your data is marked safe and how it is processed before arriving at the template.
If a value has been escaped but is not marked safe, auto-escaping will still take place and result in double-escaped
characters. If you know you have data that is already safe but not marked, be sure to wrap it in Markup or use the
|safe filter.
Jinja functions (macros, super, self.BLOCKNAME) always return template data that is marked as safe.
String literals in templates with automatic escaping are considered unsafe because native Python strings (str,
unicode, basestring) are not MarkupSafe.Markup strings with an __html__ attribute.
A control structure refers to all those things that control the flow of a program - conditionals (i.e. if/elif/else), for-
loops, as well as things like macros and blocks. With the default syntax, control structures appear inside {% ... %}
blocks.
5.11.1 For
Loop over each item in a sequence. For example, to display a list of users provided in a variable called users:
<h1>Members</h1>
<ul>
{% for user in users %}
<li>{{ user.username|e }}</li>
{% endfor %}
</ul>
As variables in templates retain their object properties, it is possible to iterate over containers like dict:
<dl>
{% for key, value in my_dict.items() %}
<dt>{{ key|e }}</dt>
<dd>{{ value|e }}</dd>
{% endfor %}
</dl>
Note, however, that Python dicts are not ordered; so you might want to either pass a sorted list of tuple s – or
a collections.OrderedDict – to the template, or use the dictsort filter.
Inside of a for-loop block, you can access some special variables:
Variable Description
loop.index The current iteration of the loop. (1 indexed)
loop.index0 The current iteration of the loop. (0 indexed)
loop.revindex The number of iterations from the end of the loop (1 indexed)
loop.revindex0 The number of iterations from the end of the loop (0 indexed)
loop.first True if first iteration.
loop.last True if last iteration.
loop.length The number of items in the sequence.
loop.cycle A helper function to cycle between a list of sequences. See the explanation below.
loop.depth Indicates how deep in a recursive loop the rendering currently is. Starts at level 1
loop.depth0 Indicates how deep in a recursive loop the rendering currently is. Starts at level 0
loop.previtem The item from the previous iteration of the loop. Undefined during the first iteration.
loop.nextitem The item from the following iteration of the loop. Undefined during the last iteration.
loop.changed(*val) True if previously called with a different value (or not called at all).
Within a for-loop, it’s possible to cycle among a list of strings/variables each time through the loop by using the special
loop.cycle helper:
{% for row in rows %}
<li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>
{% endfor %}
Since Jinja 2.1, an extra cycle helper exists that allows loop-unbound cycling. For more information, have a look at
the List of Global Functions.
Unlike in Python, it’s not possible to break or continue in a loop. You can, however, filter the sequence during iteration,
which allows you to skip items. The following example skips all the users which are hidden:
{% for user in users if not user.hidden %}
<li>{{ user.username|e }}</li>
{% endfor %}
The advantage is that the special loop variable will count correctly; thus not counting the users not iterated over.
If no iteration took place because the sequence was empty or the filtering removed all the items from the sequence,
you can render a default block by using else:
<ul>
{% for user in users %}
<li>{{ user.username|e }}</li>
{% else %}
<li><em>no users found</em></li>
{% endfor %}
</ul>
Note that, in Python, else blocks are executed whenever the corresponding loop did not break. Since Jinja loops
cannot break anyway, a slightly different behavior of the else keyword was chosen.
It is also possible to use loops recursively. This is useful if you are dealing with recursive data such as sitemaps or
RDFa. To use loops recursively, you basically have to add the recursive modifier to the loop definition and call the
loop variable with the new iterable where you want to recurse.
The following example implements a sitemap with recursive loops:
<ul class="sitemap">
{%- for item in sitemap recursive %}
(continues on next page)
The loop variable always refers to the closest (innermost) loop. If we have more than one level of loops, we can rebind
the variable loop by writing {% set outer_loop = loop %} after the loop that we want to use recursively. Then, we can
call it using {{ outer_loop(. . . ) }}
Please note that assignments in loops will be cleared at the end of the iteration and cannot outlive the loop scope.
Older versions of Jinja had a bug where in some circumstances it appeared that assignments would work. This is not
supported. See Assignments for more information about how to deal with this.
If all you want to do is check whether some value has changed since the last iteration or will change in the next
iteration, you can use previtem and nextitem:
If you only care whether the value changed at all, using changed is even easier:
5.11.2 If
The if statement in Jinja is comparable with the Python if statement. In the simplest form, you can use it to test if a
variable is defined, not empty and not false:
{% if users %}
<ul>
{% for user in users %}
<li>{{ user.username|e }}</li>
{% endfor %}
</ul>
{% endif %}
For multiple branches, elif and else can be used like in Python. You can use more complex Expressions there, too:
{% if kenny.sick %}
Kenny is sick.
{% elif kenny.dead %}
(continues on next page)
5.11.3 Macros
Macros are comparable with functions in regular programming languages. They are useful to put often used idioms
into reusable functions to not repeat yourself (“DRY”).
Here’s a small example of a macro that renders a form element:
If the macro was defined in a different template, you have to import it first.
Inside macros, you have access to three special variables:
varargs If more positional arguments are passed to the macro than accepted by the macro, they end up in the special
varargs variable as a list of values.
kwargs Like varargs but for keyword arguments. All unconsumed keyword arguments are stored in this special
variable.
caller If the macro was called from a call tag, the caller is stored in this variable as a callable macro.
Macros also expose some of their internal details. The following attributes are available on a macro object:
name The name of the macro. {{ input.name }} will print input.
arguments A tuple of the names of arguments the macro accepts.
defaults A tuple of default values.
catch_kwargs This is true if the macro accepts extra keyword arguments (i.e.: accesses the special kwargs variable).
catch_varargs This is true if the macro accepts extra positional arguments (i.e.: accesses the special varargs variable).
caller This is true if the macro accesses the special caller variable and may be called from a call tag.
If a macro name starts with an underscore, it’s not exported and can’t be imported.
5.11.4 Call
In some cases it can be useful to pass a macro to another macro. For this purpose, you can use the special call block.
The following example shows a macro that takes advantage of the call functionality and how it can be used:
It’s also possible to pass arguments back to the call block. This makes it useful as a replacement for loops. Generally
speaking, a call block works exactly like a macro without a name.
Here’s an example of how a call block can be used with arguments:
{% call(user) dump_users(list_of_user) %}
<dl>
<dl>Realname</dl>
<dd>{{ user.realname|e }}</dd>
<dl>Description</dl>
<dd>{{ user.description }}</dd>
</dl>
{% endcall %}
5.11.5 Filters
Filter sections allow you to apply regular Jinja filters on a block of template data. Just wrap the code in the special
filter section:
{% filter upper %}
This text becomes uppercase
{% endfilter %}
5.11.6 Assignments
Inside code blocks, you can also assign values to variables. Assignments at top level (outside of blocks, macros or
loops) are exported from the template like top level macros and can be imported by other templates.
Assignments use the set tag and can have multiple targets:
Scoping Behavior
Please keep in mind that it is not possible to set variables inside a block and have them show up outside of it. This
also applies to loops. The only exception to that rule are if statements which do not introduce a scope. As a result the
following template is not going to do what you might expect:
It is not possible with Jinja syntax to do this. Instead use alternative constructs like the loop else block or the special
loop variable:
As of version 2.10 more complex use cases can be handled using namespace objects which allow propagating of
changes across scopes:
{% set ns = namespace(found=false) %}
{% for item in items %}
{% if item.check_something() %}
{% set ns.found = true %}
{% endif %}
* {{ item.title }}
{% endfor %}
Found item having something: {{ ns.found }}
Note that the obj.attr notation in the set tag is only allowed for namespace objects; attempting to assign an attribute
on any other object will raise an exception.
New in version 2.10: Added support for namespace objects
{% set navigation %}
<li><a href="/">Index</a>
<li><a href="/downloads">Downloads</a>
{% endset %}
5.11.8 Extends
The extends tag can be used to extend one template from another. You can have multiple extends tags in a file, but only
one of them may be executed at a time.
See the section about Template Inheritance above.
5.11.9 Blocks
Blocks are used for inheritance and act as both placeholders and replacements at the same time. They are documented
in detail in the Template Inheritance section.
5.11.10 Include
The include tag is useful to include a template and return the rendered contents of that file into the current namespace:
{% include 'header.html' %}
Body
{% include 'footer.html' %}
Included templates have access to the variables of the active context by default. For more details about context behavior
of imports and includes, see Import Context Behavior.
From Jinja 2.2 onwards, you can mark an include with ignore missing; in which case Jinja will ignore the
statement if the template to be included does not exist. When combined with with or without context, it must
be placed before the context visibility statement. Here are some valid examples:
Changed in version 2.4: If a template object was passed to the template context, you can include that object using
include.
5.11.11 Import
Jinja supports putting often used code into macros. These macros can go into different templates and get imported
from there. This works similarly to the import statements in Python. It’s important to know that imports are cached
and imported templates don’t have access to the current template variables, just the globals by default. For more details
about context behavior of imports and includes, see Import Context Behavior.
There are two ways to import templates. You can import a complete template into a variable or request specific macros
/ exported variables from it.
Imagine we have a helper module that renders forms (called forms.html):
The easiest and most flexible way to access a template’s variables and macros is to import the whole template module
into a variable. That way, you can access the attributes:
Alternatively, you can import specific names from a template into the current namespace:
Macros and variables starting with one or more underscores are private and cannot be imported.
Changed in version 2.4: If a template object was passed to the template context, you can import from that object.
By default, included templates are passed the current context and imported templates are not. The reason for this is
that imports, unlike includes, are cached; as imports are often used just as a module that holds macros.
This behavior can be changed explicitly: by adding with context or without context to the import/include directive, the
current context can be passed to the template and caching is disabled automatically.
Here are two examples:
Note
In Jinja 2.0, the context that was passed to the included template did not include variables defined in the template. As
a matter of fact, this did not work:
The included template render_box.html is not able to access box in Jinja 2.0. As of Jinja 2.1, render_box.
html is able to do so.
5.13 Expressions
Jinja allows basic expressions everywhere. These work very similarly to regular Python; even if you’re not working
with Python you should feel comfortable with it.
5.13.1 Literals
The simplest form of expressions are literals. Literals are representations for Python objects such as strings and
numbers. The following literals exist:
"Hello World" Everything between two double or single quotes is a string. They are useful whenever you need a
string in the template (e.g. as arguments to function calls and filters, or just to extend or include a template).
42 / 123_456 Integers are whole numbers without a decimal part. The ‘_’ character can be used to separate groups
for legibility.
42.23 / 42.1e2 / 123_456.789 Floating point numbers can be written using a ‘.’ as a decimal mark. They can
also be written in scientific notation with an upper or lower case ‘e’ to indicate the exponent part. The ‘_’
character can be used to separate groups for legibility, but cannot be used in the exponent part.
['list', 'of', 'objects'] Everything between two brackets is a list. Lists are useful for storing sequential
data to be iterated over. For example, you can easily create a list of links using lists and tuples for (and with) a
for loop:
<ul>
{% for href, caption in [('index.html', 'Index'), ('about.html', 'About'),
('downloads.html', 'Downloads')] %}
<li><a href="{{ href }}">{{ caption }}</a></li>
{% endfor %}
</ul>
('tuple', 'of', 'values') Tuples are like lists that cannot be modified (“immutable”). If a tuple only has
one item, it must be followed by a comma (('1-tuple',)). Tuples are usually used to represent items of
two or more elements. See the list example above for more details.
{'dict': 'of', 'key': 'and', 'value': 'pairs'} A dict in Python is a structure that com-
bines keys and values. Keys must be unique and always have exactly one value. Dicts are rarely used in
templates; they are useful in some rare cases such as the xmlattr() filter.
Note
The special constants true, false, and none are indeed lowercase. Because that caused confusion in the past, (True
used to expand to an undefined variable that was considered false), all three can now also be written in title case (True,
False, and None). However, for consistency, (all Jinja identifiers are lowercase) you should use the lowercase versions.
5.13.2 Math
Jinja allows you to calculate with values. This is rarely useful in templates but exists for completeness’ sake. The
following operators are supported:
+ Adds two objects together. Usually the objects are numbers, but if both are strings or lists, you can concatenate
them this way. This, however, is not the preferred way to concatenate strings! For string concatenation, have a
look-see at the ~ operator. {{ 1 + 1 }} is 2.
- Subtract the second number from the first one. {{ 3 - 2 }} is 1.
/ Divide two numbers. The return value will be a floating point number. {{ 1 / 2 }} is {{ 0.5 }}.
// Divide two numbers and return the truncated integer result. {{ 20 // 7 }} is 2.
% Calculate the remainder of an integer division. {{ 11 % 7 }} is 4.
* Multiply the left operand with the right one. {{ 2 * 2 }} would return 4. This can also be used to repeat a
string multiple times. {{ '=' * 80 }} would print a bar of 80 equal signs.
** Raise the left operand to the power of the right operand. {{ 2**3 }} would return 8.
5.13.3 Comparisons
5.13.4 Logic
For if statements, for filtering, and if expressions, it can be useful to combine multiple expressions:
and Return true if the left and the right operand are true.
or Return true if the left or the right operand are true.
not negate a statement (see below).
(expr) Parentheses group an expression.
5.13. Expressions 55
Jinja Documentation (2.11.x), Release 2.11.1
Note
The is and in operators support negation using an infix notation, too: foo is not bar and foo not in bar
instead of not foo is bar and not foo in bar. All other expressions require a prefix notation: not (foo
and bar).
The following operators are very useful but don’t fit into any of the other two categories:
in Perform a sequence / mapping containment test. Returns true if the left operand is contained in the right. {{ 1
in [1, 2, 3] }} would, for example, return true.
is Performs a test.
| Applies a filter.
~ Converts all operands into strings and concatenates them.
{{ "Hello " ~ name ~ "!" }} would return (assuming name is set to 'John') Hello John!.
() Call a callable: {{ post.render() }}. Inside of the parentheses you can use positional arguments and
keyword arguments like in Python:
{{ post.render(user, full=true) }}.
. / [] Get an attribute of an object. (See Variables)
5.13.6 If Expression
It is also possible to use inline if expressions. These are useful in some situations. For example, you can use this to
extend from one template if a variable is defined, otherwise from the default layout template:
The general syntax is <do something> if <something is true> else <do something else>.
The else part is optional. If not provided, the else block implicitly evaluates into an Undefined object (regardless of
what undefined in the environment is set to):
{{ "[{}]".format(page.title) if page.title }}
You can also use any of the methods of defined on a variable’s type. The value returned from the method invocation is
used as the value of the expression. Here is an example that uses methods defined on strings (where page.title is
a string):
{{ page.title.capitalize() }}
This works for methods on user-defined types. For example, if variable f of type Foo has a method bar defined on
it, you can do the following:
{{ f.bar(value) }}
Operator methods also work as expected. For example, % implements printf-style for strings:
Although you should prefer the .format method for that case (which is a bit contrived in the context of rendering a
template):
{{ "Hello, {}!".format(name) }}
abs(x, / )
Return the absolute value of the argument.
attr(obj, name)
Get an attribute of an object. foo|attr("bar") works like foo.bar just that always an attribute is returned
and items are not looked up.
See Notes on subscriptions for more details.
batch(value, linecount, fill_with=None)
A filter that batches items. It works pretty much like slice just the other way round. It returns a list of lists with
the given number of items. If you provide a second parameter this is used to fill up missing items. See this
example:
<table>
{%- for row in items|batch(3, ' ') %}
<tr>
{%- for column in row %}
<td>{{ column }}</td>
{%- endfor %}
</tr>
{%- endfor %}
</table>
capitalize(s)
Capitalize a value. The first character will be uppercase, all others lowercase.
center(value, width=80)
Centers the value in a field of a given width.
default(value, default_value=”, boolean=False)
If the value is undefined it will return the passed default value, otherwise the value of the variable:
This will output the value of my_variable if the variable was defined, otherwise 'my_variable is not
defined'. If you want to use default with variables that evaluate to false you have to set the second parameter
to true:
Changed in version 2.11: It’s now possible to configure the Environment with ChainableUndefined to
make the default filter work on nested elements and attributes that may contain undefined values in the chain
without getting an UndefinedError.
Aliases d
dictsort(value, case_sensitive=False, by=’key’, reverse=False)
Sort a dict and yield (key, value) pairs. Because python dicts are unsorted you may want to use this function to
order them by either key or value:
escape(s)
Convert the characters &, <, >, ‘, and ” in string s to HTML-safe sequences. Use this if you need to display text
that might contain such characters in HTML. Marks return value as markup string.
Aliases e
filesizeformat(value, binary=False)
Format the value like a ‘human-readable’ file size (i.e. 13 kB, 4.1 MB, 102 Bytes, etc). Per default decimal
prefixes are used (Mega, Giga, etc.), if the second parameter is set to True the binary prefixes are used (Mebi,
Gibi).
first(seq)
Return the first item of a sequence.
float(value, default=0.0)
Convert the value into a floating point number. If the conversion doesn’t work it will return 0.0. You can
override this default using the first parameter.
forceescape(value)
Enforce HTML escaping. This will probably double escape variables.
format(value, *args, **kwargs)
Apply the given values to a printf-style format string, like string % values.
In most cases it should be more convenient and efficient to use the % operator or str.format().
groupby(value, attribute)
Group a sequence of objects by an attribute using Python’s itertools.groupby(). The attribute can use
dot notation for nested access, like "address.city". Unlike Python’s groupby, the values are sorted first
so only one group is returned for each unique value.
For example, a list of User objects with a city attribute can be rendered in groups. In this example, grouper
refers to the city value of the group.
groupby yields namedtuples of (grouper, list), which can be used instead of the tuple unpacking
above. grouper is the value of the attribute, and list is the items with that value.
Changed in version 2.6: The attribute supports dot notation for nested access.
indent(s, width=4, first=False, blank=False, indentfirst=None)
Return a copy of the string with each line indented by 4 spaces. The first line and blank lines are not indented
by default.
Parameters
• width – Number of spaces to indent by.
• first – Don’t skip indenting the first line.
• blank – Don’t skip indenting empty lines.
Changed in version 2.10: Blank lines are not indented by default.
Rename the indentfirst argument to first.
int(value, default=0, base=10)
Convert the value into an integer. If the conversion doesn’t work it will return 0. You can override this default
using the first parameter. You can also override the default base (10) in the second parameter, which handles
input with prefixes such as 0b, 0o and 0x for bases 2, 8 and 16 respectively. The base is ignored for decimal
numbers and non-string values.
join(value, d=”, attribute=None)
Return a string which is the concatenation of the strings in the sequence. The separator between elements is an
empty string per default, you can define it with the optional parameter:
{{ [1, 2, 3]|join('|') }}
-> 1|2|3
{{ [1, 2, 3]|join }}
-> 123
length(obj, / )
Return the number of items in a container.
Aliases count
list(value)
Convert the value into a list. If it was a string the returned list will be a list of characters.
lower(s)
Convert a value to lowercase.
map(*args, **kwargs)
Applies a filter on a sequence of objects or looks up an attribute. This is useful when dealing with lists of objects
but you are really only interested in a certain value of it.
The basic usage is mapping on an attribute. Imagine you have a list of users but you are only interested in a list
of usernames:
You can specify a default value to use if an object in the list does not have the given attribute.
Alternatively you can let it invoke a filter by passing the name of the filter and the arguments afterwards. A good
example would be applying a text conversion filter on a sequence:
{{ [1, 2, 3]|max }}
-> 3
Parameters
• case_sensitive – Treat upper and lower case strings as distinct.
• attribute – Get the object with the max value of this attribute.
{{ [1, 2, 3]|min }}
-> 1
Parameters
• case_sensitive – Treat upper and lower case strings as distinct.
• attribute – Get the object with the min value of this attribute.
pprint(value, verbose=False)
Pretty print a variable. Useful for debugging.
With Jinja 1.2 onwards you can pass it a parameter. If this parameter is truthy the output will be more verbose
(this requires pretty)
random(seq)
Return a random item from the sequence.
reject(*args, **kwargs)
Filters a sequence of objects by applying a test to each object, and rejecting the objects with the test succeeding.
If no test is specified, each object will be evaluated as a boolean.
Example usage:
{{ numbers|reject("odd") }}
{{ users|rejectattr("is_active") }}
{{ users|rejectattr("email", "none") }}
reverse(value)
Reverse the object or return an iterator that iterates over it the other way round.
round(value, precision=0, method=’common’)
Round the number to a given precision. The first parameter specifies the precision (default is 0), the second the
rounding method:
• 'common' rounds either up or down
• 'ceil' always rounds up
• 'floor' always rounds down
If you don’t specify a method 'common' is used.
{{ 42.55|round }}
-> 43.0
{{ 42.55|round(1, 'floor') }}
-> 42.5
Note that even if rounded to 0 precision, a float is returned. If you need a real integer, pipe it through int:
{{ 42.55|round|int }}
-> 43
safe(value)
Mark the value as safe which means that in an environment with automatic escaping enabled this variable will
not be escaped.
select(*args, **kwargs)
Filters a sequence of objects by applying a test to each object, and only selecting the objects with the test
succeeding.
If no test is specified, each object will be evaluated as a boolean.
Example usage:
{{ numbers|select("odd") }}
{{ numbers|select("odd") }}
{{ numbers|select("divisibleby", 3) }}
{{ numbers|select("lessthan", 42) }}
{{ strings|select("equalto", "mystring") }}
Example usage:
{{ users|selectattr("is_active") }}
{{ users|selectattr("email", "none") }}
<div class="columnwrapper">
{%- for column in items|slice(3) %}
<ul class="column-{{ loop.index }}">
{%- for item in column %}
<li>{{ item }}</li>
{%- endfor %}
</ul>
{%- endfor %}
</div>
If you pass it a second argument it’s used to fill missing values on the last iteration.
sort(value, reverse=False, case_sensitive=False, attribute=None)
Sort an iterable using Python’s sorted().
Parameters
• reverse – Sort descending instead of ascending.
• case_sensitive – When sorting strings, sort upper and lower case separately.
• attribute – When sorting objects or dicts, an attribute or key to sort by. Can use dot
notation like "address.city". Can be a list of attributes like "age,name".
The sort is stable, it does not change the relative order of elements that compare equal. This makes it is possible
to chain sorts on different attributes and ordering.
As a shortcut to chaining when the direction is the same for all attributes, pass a comma separate list of attributes.
Changed in version 2.11.0: The attribute parameter can be a comma separated list of attributes, e.g. "age,
name".
Changed in version 2.6: The attribute parameter was added.
string(object)
Make a string unicode if it isn’t already. That way a markup string is not converted back to unicode.
striptags(value)
Strip SGML/XML tags and replace adjacent whitespace by one space.
sum(iterable, attribute=None, start=0)
Returns the sum of a sequence of numbers plus the value of parameter ‘start’ (which defaults to 0). When the
sequence is empty it returns start.
It is also possible to sum up only certain attributes:
Total: {{ items|sum(attribute='price') }}
Changed in version 2.6: The attribute parameter was added to allow suming up over attributes. Also the start
parameter was moved on to the right.
title(s)
Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are
lowercase.
tojson(value, indent=None)
Dumps a structure to JSON so that it’s safe to use in <script> tags. It accepts the same arguments and returns
a JSON string. Note that this is available in templates through the |tojson filter which will also mark the
result as safe. Due to how this function escapes certain characters this is safe even if used outside of <script>
tags.
The following characters are escaped in strings:
• <
• >
• &
• '
This makes it safe to embed such strings in any place in HTML with the notable exception of double quoted
attributes. In that case single quote your attributes or HTML escape it in addition.
The indent parameter can be used to enable pretty printing. Set it to the number of spaces that the structures
should be indented with.
Note that this filter is for use in HTML contexts only.
New in version 2.9.
trim(value, chars=None)
Strip leading and trailing characters, by default whitespace.
truncate(s, length=255, killwords=False, end=’...’, leeway=None)
Return a truncated copy of the string. The length is specified with the first parameter which defaults to 255.
If the second parameter is true the filter will cut the text at length. Otherwise it will discard the last word. If
the text was in fact truncated it will append an ellipsis sign ("..."). If you want a different ellipsis sign than
"..." you can specify it using the third parameter. Strings that only exceed the length by the tolerance margin
given in the fourth parameter will not be truncated.
The default leeway on newer Jinja versions is 5 and was 0 before but can be reconfigured globally.
unique(value, case_sensitive=False, attribute=None)
Returns a list of unique items from the given iterable.
The unique items are yielded in the same order as their first occurrence in the iterable passed to the filter.
Parameters
• case_sensitive – Treat upper and lower case strings as distinct.
• attribute – Filter objects with unique values for this attribute.
upper(s)
Convert a value to uppercase.
urlencode(value)
Quote data for use in a URL path or query using UTF-8.
Basic wrapper around urllib.parse.quote() when given a string, or urllib.parse.
urlencode() for a dict or iterable.
Parameters value – Data to quote. A string will be quoted directly. A dict or iterable of (key,
value) pairs will be joined as a query string.
When given a string, “/” is not quoted. HTTP servers treat “/” and “%2F” equivalently in paths. If you need
quoted slashes, use the |replace("/", "%2F") filter.
New in version 2.7.
urlize(value, trim_url_limit=None, nofollow=False, target=None, rel=None)
Converts URLs in plain text into clickable links.
If you pass the filter an additional integer it will shorten the urls to that number. Also a third argument exists
that makes the urls “nofollow”:
{{ mytext|urlize(40, true) }}
links are shortened to 40 chars and defined with rel="nofollow"
If target is specified, the target attribute will be added to the <a> tag:
{{ mytext|urlize(40, target='_blank') }}
Parameters
• s – Original text to wrap.
• width – Maximum length of wrapped lines.
• break_long_words – If a word is longer than width, break it across lines.
• break_on_hyphens – If a word contains hyphens, it may be split across lines.
• wrapstring – String to join each wrapped line. Defaults to Environment.
newline_sequence.
Changed in version 2.11: Existing newlines are treated as paragraphs wrapped separately.
Changed in version 2.11: Added the break_on_hyphens parameter.
Changed in version 2.7: Added the wrapstring parameter.
xmlattr(d, autospace=True)
Create an SGML/XML attribute string based on the items in a dict. All values that are neither none nor undefined
are automatically escaped:
As you can see it automatically prepends a space in front of the item if the filter returned something unless the
second parameter is false.
boolean(value)
Return true if the object is a boolean value.
New in version 2.11.
callable(obj, / )
Return whether the object is callable (i.e., some kind of function).
Note that classes are callable, as are instances of classes with a __call__() method.
defined(value)
Return true if the variable is defined:
{% if variable is defined %}
value of variable: {{ variable }}
{% else %}
variable is not defined
{% endif %}
See the default() filter for a simple way to set undefined variables.
divisibleby(value, num)
Check if a variable is divisible by a number.
eq(a, b, / )
Same as a == b.
Aliases ==, equalto
escaped(value)
Check if the value is escaped.
even(value)
Return true if the variable is even.
false(value)
Return true if the object is False.
New in version 2.11.
float(value)
Return true if the object is a float.
New in version 2.11.
ge(a, b, / )
Same as a >= b.
Aliases >=
gt(a, b, / )
Same as a > b.
Aliases >, greaterthan
in(value, seq)
Check if value is in seq.
New in version 2.10.
integer(value)
Return true if the object is an integer.
New in version 2.11.
iterable(value)
Check if it’s possible to iterate over an object.
le(a, b, / )
Same as a <= b.
Aliases <=
lower(value)
Return true if the variable is lowercased.
lt(a, b, / )
Same as a < b.
sequence(value)
Return true if the variable is a sequence. Sequences are variables that are iterable.
string(value)
Return true if the object is a string.
true(value)
Return true if the object is True.
New in version 2.11.
undefined(value)
Like defined() but the other way round.
upper(value)
Return true if the variable is uppercased.
<ul>
{% for user in users %}
<li>{{ user.username }}</li>
{% endfor %}
{% for number in range(10 - users|count) %}
<li class="empty"><span>...</span></li>
{% endfor %}
</ul>
Parameters items – Each positional argument will be yielded in the order given for each cycle.
{% set ns = namespace() %}
{% set ns.foo = 'bar' %}
The main purpose of this is to allow carrying a value from within a loop body to an outer scope. Initial values
can be provided as a dict, as keyword arguments, or both (same behavior as Python’s dict constructor):
{% set ns = namespace(found=false) %}
{% for item in items %}
{% if item.check_something() %}
{% set ns.found = true %}
{% endif %}
* {{ item.title }}
{% endfor %}
Found item having something: {{ ns.found }}
5.17 Extensions
The following sections cover the built-in Jinja extensions that may be enabled by an application. An application could
also provide further extensions not covered by this documentation; in which case there should be a separate document
explaining said extensions.
5.17.1 i18n
If the i18n Extension is enabled, it’s possible to mark text in the template as translatable. To mark a section as
translatable, use a trans block:
Inside the block, no statements are allowed, only text and simple variable tags.
Variable tags can only be a name, not attribute access, filters, or other expressions. To use an expression, bind it to a
name in the trans tag for use in the block.
To bind more than one expression, separate each with a comma (,).
To pluralize, specify both the singular and plural forms separated by the pluralize tag.
{% trans count=list|length %}
There is {{ count }} {{ name }} object.
{% pluralize %}
There are {{ count }} {{ name }} objects.
{% endtrans %}
By default, the first variable in a block is used to determine whether to use singular or plural form. If that isn’t correct,
specify the variable used for pluralizing as a parameter to pluralize.
When translating blocks of text, whitespace and linebreaks result in hard to read and error-prone translation strings. To
avoid this, a trans block can be marked as trimmed, which will replace all linebreaks and the whitespace surrounding
them with a single space and remove leading and trailing whitespace.
This results in This is %(book_title)s. You should read it! in the translation file.
If trimming is enabled globally, the notrimmed modifier can be used to disable it for a block.
New in version 2.10: The trimmed and notrimmed modifiers have been added.
It’s possible to translate strings in expressions with these functions:
• gettext: translate a single string
• ngettext: translate a pluralizable string
• _: alias for gettext
You can print a translated string like this:
{{ _("Hello, World!") }}
{{ _("Hello, %(user)s!")|format(user=user.username) }}
Always use keyword arguments to format, as other languages may not use the words in the same order.
If New Style Gettext calls are activated, using placeholders is easier. Formatting is part of the gettext call instead
of using the format filter.
{{ gettext('Hello World!') }}
{{ gettext('Hello %(name)s!', name='World') }}
{{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }}
The ngettext function’s format string automatically receives the count as a num parameter in addition to the given
parameters.
If the expression-statement extension is loaded, a tag called do is available that works exactly like the regular variable
expression ({{ ... }}); except it doesn’t print anything. This can be used to modify lists:
5.17. Extensions 71
Jinja Documentation (2.11.x), Release 2.11.1
{% do navigation.append('a string') %}
If the application enables the Loop Controls, it’s possible to use break and continue in loops. When break is reached,
the loop is terminated; if continue is reached, the processing is stopped and continues with the next iteration.
Here’s a loop that skips every second item:
{% for user in users %}
{%- if loop.index is even %}{% continue %}{% endif %}
...
{% endfor %}
Note that loop.index starts with 1, and loop.index0 starts with 0 (See: For).
If the Debug Extension is enabled, a {% debug %} tag will be available to dump the current context as well as the
available filters and tests. This is useful to see what’s available to use in the template without setting up a debugger.
<pre>{% debug %}</pre>
Because it is common to set variables at the beginning of the scope, you can do that within the with statement. The
following two examples are equivalent:
{% with foo = 42 %}
{{ foo }}
{% endwith %}
{% with %}
{% set foo = 42 %}
{{ foo }}
{% endwith %}
An important note on scoping here. In Jinja versions before 2.9 the behavior of referencing one variable to another
had some unintended consequences. In particular one variable could refer to another defined in the same with block’s
opening statement. This caused issues with the cleaned up scoping behavior and has since been improved. In particular
in newer Jinja versions the following code always refers to the variable a from outside the with block:
In earlier Jinja versions the b attribute would refer to the results of the first attribute. If you depend on this behavior
you can rewrite it to use the set tag:
{% with a={} %}
{% set b = a.attribute %}
{% endwith %}
Extension
In older versions of Jinja (before 2.9) it was required to enable this feature with an extension. It’s now enabled by
default.
{% autoescape true %}
Autoescaping is active within this block
{% endautoescape %}
{% autoescape false %}
Autoescaping is inactive within this block
{% endautoescape %}
Extension
In older versions of Jinja (before 2.9) it was required to enable this feature with an extension. It’s now enabled by
default.
SIX
EXTENSIONS
Jinja supports extensions that can add extra filters, tests, globals or even extend the parser. The main motivation of
extensions is to move often used code into a reusable class like adding support for internationalization.
Extensions are added to the Jinja environment at creation time. Once the environment is created additional extensions
cannot be added. To add an extension pass a list of extension classes or import paths to the extensions parameter of
the Environment constructor. The following example creates a Jinja environment with the i18n extension loaded:
jinja_env = Environment(extensions=['jinja2.ext.i18n'])
After enabling the extension, the environment provides the following additional methods:
jinja2.Environment.install_gettext_translations(translations, newstyle=False)
Installs a translation globally for the environment. The translations object must implement gettext and
ngettext (or ugettext and ungettext for Python 2). gettext.NullTranslations, gettext.
GNUTranslations, and Babels Translations are supported.
Changed in version 2.5: Added new-style gettext support.
jinja2.Environment.install_null_translations(newstyle=False)
Install no-op gettext functions. This is useful if you want to prepare the application for internationalization but
don’t want to implement the full system yet.
Changed in version 2.5: Added new-style gettext support.
75
Jinja Documentation (2.11.x), Release 2.11.1
translations = get_gettext_translations()
env = Environment(extensions=["jinja2.ext.i18n"])
env.install_gettext_translations(translations)
The get_gettext_translations function would return the translator for the current configuration, for example
by using gettext.find.
The usage of the i18n extension for template designers is covered in the template documentation.
76 Chapter 6. Extensions
Jinja Documentation (2.11.x), Release 2.11.1
{{ gettext("Hello, World!") }}
{{ gettext("Hello, %(name)s!")|format(name=name) }}
{{ ngettext(
"%(num)d apple", "%(num)d apples", apples|count
)|format(num=apples|count) }}
New style gettext make formatting part of the call, and behind the scenes enforce more consistency.
{{ gettext("Hello, World!") }}
{{ gettext("Hello, %(name)s!", name=name) }}
{{ ngettext("%(num)d apple", "%(num)d apples", apples|count) }}
By writing extensions you can add custom tags to Jinja. This is a non-trivial task and usually not needed as the default
tags and expressions cover all common use cases. The i18n extension is a good example of why extensions are useful.
Another one would be fragment caching.
When writing extensions you have to keep in mind that you are working with the Jinja template compiler which
does not validate the node tree you are passing to it. If the AST is malformed you will get all kinds of compiler or
runtime errors that are horrible to debug. Always make sure you are using the nodes you create correctly. The API
documentation below shows which nodes exist and how to use them.
6.9.1 Cache
The following example implements a cache tag for Jinja by using the cachelib library:
class FragmentCacheExtension(Extension):
# a set of names that trigger the extension.
tags = {"cache"}
78 Chapter 6. Extensions
Jinja Documentation (2.11.x), Release 2.11.1
env = Environment(extensions=[FragmentCacheExtension])
env.fragment_cache = SimpleCache()
Inside the template it’s then possible to mark blocks as cacheable. The following example caches a sidebar for 300
seconds:
The following example demonstrates using Extension.filter_stream() to parse calls to the _() gettext
function inline with static data without needing Jinja blocks.
<h1>_(Welcome)</h1>
<p>_(This is a paragraph)</p>
_outside_re = re.compile(r"\\?(gettext|_)\(")
_inside_re = re.compile(r"\\?[()]")
class InlineGettext(Extension):
"""This extension implements support for inline gettext blocks::
<h1>_(Welcome)</h1>
<p>_(This is a paragraph)</p>
pos = 0
lineno = token.lineno
while 1:
if not paren_stack:
match = _outside_re.search(token.value, pos)
else:
match = _inside_re.search(token.value, pos)
if match is None:
break
new_pos = match.start()
if new_pos > pos:
preval = token.value[pos:new_pos]
yield Token(lineno, "data", preval)
lineno += count_newlines(preval)
gtok = match.group()
if gtok[0] == "\\":
yield Token(lineno, "data", gtok[1:])
elif not paren_stack:
yield Token(lineno, "block_begin", None)
yield Token(lineno, "name", "trans")
yield Token(lineno, "block_end", None)
paren_stack = 1
else:
if gtok == "(" or paren_stack > 1:
yield Token(lineno, "data", gtok)
paren_stack += gtok == ")" and -1 or 1
(continues on next page)
80 Chapter 6. Extensions
Jinja Documentation (2.11.x), Release 2.11.1
if paren_stack:
raise TemplateSyntaxError(
"unclosed gettext expression",
token.lineno,
stream.name,
stream.filename,
)
6.10.1 Extension
self.attr('_my_attribute', lineno=lineno)
filter_stream(stream)
It’s passed a TokenStream that can be used to filter tokens returned. This method has to return an
iterable of Tokens, but it doesn’t have to return a TokenStream.
parse(parser)
If any of the tags matched this method is called with the parser as first argument. The token the parser
stream is pointing at is the name token that matched. This method has to return one or a list of multiple
nodes.
preprocess(source, name, filename=None)
This method is called before the actual lexing and can be used to preprocess the source. The filename is
optional. The return value must be the preprocessed source.
6.10.2 Parser
The parser passed to Extension.parse() provides ways to parse expressions of different types. The following
methods may be used by extensions:
class jinja2.parser.Parser(environment, source, name=None, filename=None, state=None)
This is the central parsing class Jinja uses. It’s passed to extensions and can be used to parse expressions or
statements.
filename
The filename of the template the parser processes. This is not the load name of the template. For the load
name see name. For templates that were not loaded form the file system this is None.
name
The load name of the template.
stream
The current TokenStream
fail(msg, lineno=None, exc=<class ’jinja2.exceptions.TemplateSyntaxError’>)
Convenience method that raises exc with the message, passed line number or last line number as well as
the current name and filename.
free_identifier(lineno=None)
Return a new free identifier as InternalName.
parse_assign_target(with_tuple=True, name_only=False, extra_end_rules=None,
with_namespace=False)
Parse an assignment target. As Jinja allows assignments to tuples, this function can parse all allowed
assignment targets. Per default assignments to tuples are parsed, that can be disable however by set-
ting with_tuple to False. If only assignments to names are wanted name_only can be set to True. The
extra_end_rules parameter is forwarded to the tuple parsing function. If with_namespace is enabled, a
namespace assignment may be parsed.
parse_expression(with_condexpr=True)
Parse an expression. Per default all expressions are parsed, if the optional with_condexpr parameter is set
to False conditional expressions are not parsed.
parse_statements(end_tokens, drop_needle=False)
Parse multiple statements into a list until one of the end tokens is reached. This is used to parse the body
of statements as it also parses template data if appropriate. The parser checks first if the current token is a
colon and skips it if there is one. Then it checks for the block end and parses until if one of the end_tokens
is reached. Per default the active token in the stream at the end of the call is the matched end token. If this
is not wanted drop_needle can be set to True and the end token is removed.
82 Chapter 6. Extensions
Jinja Documentation (2.11.x), Release 2.11.1
test(expr)
Test a token against a token expression. This can either be a token type or
'token_type:token_value'. This can only test against string values and types.
test_any(*iterable)
Test against multiple token expressions.
There is also a utility function in the lexer module that can count newline characters in strings:
jinja2.lexer.count_newlines(value)
Count the number of newline characters in the string. This is useful for extensions that filter a stream.
6.10.3 AST
The AST (Abstract Syntax Tree) is used to represent a template after parsing. It’s build of nodes that the compiler then
converts into executable Python code objects. Extensions that provide custom statements can return nodes to execute
custom Python code.
The list below describes all nodes that are currently available. The AST may change between Jinja versions but will
stay backwards compatible.
For more information have a look at the repr of jinja2.Environment.parse().
class jinja2.nodes.Node
Baseclass for all Jinja nodes. There are a number of nodes available of different types. There are four major
types:
• Stmt: statements
• Expr: expressions
• Helper: helper nodes
• Template: the outermost wrapper node
All nodes have fields and attributes. Fields may be other nodes, lists, or arbitrary values. Fields are passed to
the constructor as regular positional arguments, attributes as keyword arguments. Each node has two attributes:
lineno (the line number of the node) and environment. The environment attribute is set at the end of the parsing
process for all nodes automatically.
find(node_type)
Find the first node of a given type. If no such node exists the return value is None.
find_all(node_type)
Find all the nodes of a given type. If the type is a tuple, the check is performed for any of the tuple items.
iter_child_nodes(exclude=None, only=None)
Iterates over all direct child nodes of the node. This iterates over all fields and yields the values of they are
nodes. If the value of a field is a list all the nodes in that list are returned.
iter_fields(exclude=None, only=None)
This method iterates over all fields that are defined and yields (key, value) tuples. Per default all
fields are returned, but it’s possible to limit that to some fields by providing the only parameter or to
exclude some using the exclude parameter. Both should be sets or tuples of field names.
set_ctx(ctx)
Reset the context of a node and all child nodes. Per default the parser will all generate nodes that have a
‘load’ context as it’s the most common one. This method is used in the parser to set assignment targets
and other nodes to a store context.
set_environment(environment)
Set the environment for all nodes.
84 Chapter 6. Extensions
Jinja Documentation (2.11.x), Release 2.11.1
set_lineno(lineno, override=False)
Set the line numbers of the node and children.
class jinja2.nodes.Expr
Baseclass for all expressions.
Node type Node
as_const(eval_ctx=None)
Return the value of the expression as constant or raise Impossible if this was not possible.
An EvalContext can be provided, if none is given a default context is created which requires the nodes
to have an attached environment.
Changed in version 2.4: the eval_ctx parameter was added.
can_assign()
Check if it’s possible to assign something to this node.
class jinja2.nodes.BinExpr(left, right)
Baseclass for all binary expressions.
Node type Expr
class jinja2.nodes.Add(left, right)
Add the left to the right node.
Node type BinExpr
class jinja2.nodes.And(left, right)
Short circuited AND.
Node type BinExpr
class jinja2.nodes.Div(left, right)
Divides the left by the right node.
Node type BinExpr
class jinja2.nodes.FloorDiv(left, right)
Divides the left by the right node and truncates conver the result into an integer by truncating.
Node type BinExpr
class jinja2.nodes.Mod(left, right)
Left modulo right.
Node type BinExpr
class jinja2.nodes.Mul(left, right)
Multiplies the left with the right node.
Node type BinExpr
class jinja2.nodes.Or(left, right)
Short circuited OR.
Node type BinExpr
class jinja2.nodes.Pow(left, right)
Left to the power of right.
Node type BinExpr
class jinja2.nodes.Sub(left, right)
Subtract the right from the left node.
Assign(Name('foo', ctx='store'),
Getattr(ContextReference(), 'name'))
This is basically equivalent to using the contextfunction() decorator when using the high-level API,
which causes a reference to the context to be passed as the first argument to a function.
Node type Expr
class jinja2.nodes.DerivedContextReference
Return the current template context including locals. Behaves exactly like ContextReference, but includes
local variables, such as from a for loop.
New in version 2.11.
Node type Expr
class jinja2.nodes.EnvironmentAttribute(name)
Loads an attribute from the environment object. This is useful for extensions that want to call a callback stored
on the environment.
Node type Expr
class jinja2.nodes.ExtensionAttribute(identifier, name)
Returns the attribute of an extension bound to the environment. The identifier is the identifier of the
Extension.
This node is usually constructed by calling the attr() method on an extension.
Node type Expr
class jinja2.nodes.Filter(node, name, args, kwargs, dyn_args, dyn_kwargs)
This node applies a filter on an expression. name is the name of the filter, the rest of the fields are the same as
for Call.
86 Chapter 6. Extensions
Jinja Documentation (2.11.x), Release 2.11.1
If the node of a filter is None the contents of the last buffer are filtered. Buffers are created by macros and filter
blocks.
Node type Expr
class jinja2.nodes.Getattr(node, attr, ctx)
Get an attribute or item from an expression that is a ascii-only bytestring and prefer the attribute.
Node type Expr
class jinja2.nodes.Getitem(node, arg, ctx)
Get an attribute or item from an expression and prefer the item.
Node type Expr
class jinja2.nodes.ImportedName(importname)
If created with an import name the import name is returned on node access. For example
ImportedName('cgi.escape') returns the escape function from the cgi module on evaluation. Imports
are optimized by the compiler so there is no need to assign them to local variables.
Node type Expr
class jinja2.nodes.InternalName(name)
An internal name in the compiler. You cannot create these nodes yourself but the parser provides a
free_identifier() method that creates a new identifier for you. This identifier is not available from
the template and is not threated specially by the compiler.
Node type Expr
class jinja2.nodes.Literal
Baseclass for literals.
Node type Expr
class jinja2.nodes.Const(value)
All constant values. The parser will return this node for simple constants such as 42 or "foo" but it can be
used to store more complex values such as lists too. Only constants with a safe representation (objects where
eval(repr(x)) == x is true).
Node type Literal
class jinja2.nodes.Dict(items)
Any dict literal such as {1: 2, 3: 4}. The items must be a list of Pair nodes.
Node type Literal
class jinja2.nodes.List(items)
Any list literal such as [1, 2, 3]
Node type Literal
class jinja2.nodes.TemplateData(data)
A constant template string.
Node type Literal
class jinja2.nodes.Tuple(items, ctx)
For loop unpacking and some other things like multiple arguments for subscripts. Like for Name ctx specifies if
the tuple is used for loading the names or storing.
Node type Literal
class jinja2.nodes.MarkSafe(expr)
Mark the wrapped expression as safe (wrap it as Markup).
88 Chapter 6. Extensions
Jinja Documentation (2.11.x), Release 2.11.1
EvalContextModifier(options=[Keyword('autoescape', Const(True))])
class jinja2.nodes.ExprStmt(node)
A statement that evaluates an expression and discards the result.
Node type Stmt
class jinja2.nodes.Extends(template)
Represents an extends statement.
Node type Stmt
class jinja2.nodes.FilterBlock(body, filter)
Node for filter sections.
Node type Stmt
class jinja2.nodes.For(target, iter, body, else_, test, recursive)
The for loop. target is the target for the iteration (usually a Name or Tuple), iter the iterable. body is a list of
nodes that are used as loop-body, and else_ a list of nodes for the else block. If no else node exists it has to be
an empty list.
For filtered nodes an expression can be stored as test, otherwise None.
Node type Stmt
class jinja2.nodes.FromImport(template, names, with_context)
A node that represents the from import tag. It’s important to not pass unsafe names to the name attribute. The
compiler translates the attribute lookups directly into getattr calls and does not use the subscript callback of the
interface. As exported variables may not start with double underscores (which the parser asserts) this is not a
problem for regular Jinja code, but if this node is used in an extension extra care must be taken.
The list of names may contain tuples if aliases are wanted.
Node type Stmt
class jinja2.nodes.If(test, body, elif_, else_)
If test is true, body is rendered, else else_.
Node type Stmt
class jinja2.nodes.Import(template, target, with_context)
A node that represents the import tag.
Node type Stmt
class jinja2.nodes.Include(template, with_context, ignore_missing)
A node that represents the include tag.
Node type Stmt
class jinja2.nodes.Macro(name, args, defaults, body)
A macro definition. name is the name of the macro, args a list of arguments and defaults a list of defaults if
there are any. body is a list of nodes for the macro body.
Node type Stmt
class jinja2.nodes.Output(nodes)
A node that holds multiple expressions which are then printed out. This is used both for the print statement and
the regular template data.
Node type Stmt
class jinja2.nodes.OverlayScope(context, body)
An overlay scope for extensions. This is a largely unoptimized scope that however can be used to introduce
completely arbitrary variables into a sub scope from a dictionary or dictionary like object. The context field has
to evaluate to a dictionary object.
90 Chapter 6. Extensions
Jinja Documentation (2.11.x), Release 2.11.1
Example usage:
OverlayScope(context=self.call_method('get_context'),
body=[...])
92 Chapter 6. Extensions
CHAPTER
SEVEN
INTEGRATION
Jinja provides some code for integration into other tools such as frameworks, the Babel library or your favourite editor
for fancy code highlighting. This is a brief description of whats included.
Files to help integration are available here.
Jinja provides support for extracting gettext messages from templates via a Babel extractor entry point called
jinja2.ext.babel_extract. The Babel support is implemented as part of the i18n Extension extension.
Gettext messages extracted from both trans tags and code expressions.
To extract gettext messages from templates, the project needs a Jinja section in its Babel extraction method mapping
file:
[jinja2: **/templates/**.html]
encoding = utf-8
The syntax related options of the Environment are also available as configuration values in the mapping file. For
example to tell the extraction that templates use % as line_statement_prefix you can use this code:
[jinja2: **/templates/**.html]
encoding = utf-8
line_statement_prefix = %
Extensions may also be defined by passing a comma separated list of import paths as extensions value. The i18n
extension is added automatically.
Changed in version 2.7: Until 2.7 template syntax errors were always ignored. This was done since many people
are dropping non template html files into the templates folder and it would randomly fail. The assumption was that
testsuites will catch syntax errors in templates anyways. If you don’t want that behavior you can add silent=false
to the settings and exceptions are propagated.
7.2 Pylons
With Pylons 0.9.7 onwards it’s incredible easy to integrate Jinja into a Pylons powered application.
The template engine is configured in config/environment.py. The configuration for Jinja looks something like that:
93
Jinja Documentation (2.11.x), Release 2.11.1
After that you can render Jinja templates by using the render_jinja function from the pylons.templating module.
Additionally it’s a good idea to set the Pylons’ c object into strict mode. Per default any attribute to not existing
attributes on the c object return an empty string and not an undefined object. To change this just use this snippet and
add it into your config/environment.py:
config['pylons.strict_c'] = True
7.3 TextMate
There is a bundle for TextMate that supports syntax highlighting for Jinja 1 and Jinja 2 for text based templates as well
as HTML. It also contains a few often used snippets.
7.4 Vim
A syntax plugin for Vim is available from the jinja repository. The script supports Jinja 1 and Jinja 2. Once installed,
two file types are available (jinja and htmljinja). The first one is for text-based templates and the second is for
HTML templates. For HTML documents, the plugin attempts to automatically detect Jinja syntax inside of existing
HTML documents.
If you are using a plugin manager like Pathogen, see the vim-jinja repository for installing in the bundle/ directory.
94 Chapter 7. Integration
CHAPTER
EIGHT
If you have used a different template engine in the past and want to switch to Jinja here is a small guide that shows the
basic syntactic and semantic changes between some common, similar text template engines for Python.
8.1 Jinja 1
Jinja 2 is mostly compatible with Jinja 1 in terms of API usage and template syntax. The differences between Jinja 1
and 2 are explained in the following list.
8.1.1 API
Loaders Jinja 2 uses a different loader API. Because the internal representation of templates changed there is no
longer support for external caching systems such as memcached. The memory consumed by templates is com-
parable with regular Python modules now and external caching doesn’t give any advantage. If you have used a
custom loader in the past have a look at the new loader API.
Loading templates from strings In the past it was possible to generate templates from a string with the default
environment configuration by using jinja.from_string. Jinja 2 provides a Template class that can be used
to do the same, but with optional additional configuration.
Automatic unicode conversion Jinja 1 performed automatic conversion of bytestrings in a given encoding into uni-
code objects. This conversion is no longer implemented as it was inconsistent as most libraries are using the
regular Python ASCII bytestring to Unicode conversion. An application powered by Jinja 2 has to use unicode
internally everywhere or make sure that Jinja 2 only gets unicode strings passed.
i18n Jinja 1 used custom translators for internationalization. i18n is now available as Jinja 2 extension and uses a
simpler, more gettext friendly interface and has support for babel. For more details see i18n Extension.
Internal methods Jinja 1 exposed a few internal methods on the environment object such as call_function,
get_attribute and others. While they were marked as being an internal method it was possible to override
them. Jinja 2 doesn’t have equivalent methods.
Sandbox Jinja 1 was running sandbox mode by default. Few applications actually used that feature so it became
optional in Jinja 2. For more details about the sandboxed execution see SandboxedEnvironment.
Context Jinja 1 had a stacked context as storage for variables passed to the environment. In Jinja 2 a similar object
exists but it doesn’t allow modifications nor is it a singleton. As inheritance is dynamic now multiple context
objects may exist during template evaluation.
Filters and Tests Filters and tests are regular functions now. It’s no longer necessary and allowed to use factory
functions.
95
Jinja Documentation (2.11.x), Release 2.11.1
8.1.2 Templates
Jinja 2 has mostly the same syntax as Jinja 1. What’s different is that macros require parentheses around the argument
list now.
Additionally Jinja 2 allows dynamic inheritance now and dynamic includes. The old helper function rendertemplate
is gone now, include can be used instead. Includes no longer import macros and variable assignments, for that the new
import tag is used. This concept is explained in the Import documentation.
Another small change happened in the for-tag. The special loop variable doesn’t have a parent attribute, instead you
have to alias the loop yourself. See Accessing the parent Loop for more details.
8.2 Django
If you have previously worked with Django templates, you should find Jinja very familiar. In fact, most of the syntax
elements look and work the same.
However, Jinja provides some more syntax elements covered in the documentation and some work a bit different.
This section covers the template changes. As the API is fundamentally different we won’t cover it here.
In Django method calls work implicitly, while Jinja requires the explicit Python syntax. Thus this Django code:
This allows you to pass variables to the method, which is not possible in Django. This syntax is also used for macros.
Jinja provides more than one argument for filters. Also the syntax for argument passing is different. A template that
looks like this in Django:
{{ items|join:", " }}
{{ items|join(', ') }}
It is a bit more verbose, but it allows different types of arguments - including variables - and more than one of them.
8.2.3 Tests
In addition to filters there also are tests you can perform using the is operator. Here are some examples:
{% if user.user_id is odd %}
{{ user.username|e }} is odd
{% else %}
hmm. {{ user.username|e }} looks pretty normal
{% endif %}
8.2.4 Loops
For loops work very similarly to Django, but notably the Jinja special variable for the loop context is called loop, not
forloop as in Django.
In addition, the Django empty argument is called else in Jinja. For example, the Django template:
8.2.5 Cycle
The {% cycle %} tag does not exist in Jinja; however, you can achieve the same output by using the cycle method
on the loop context special variable.
The following Django template:
8.3 Mako
If you have used Mako so far and want to switch to Jinja you can configure Jinja to look more like Mako:
8.3. Mako 97
Jinja Documentation (2.11.x), Release 2.11.1
With an environment configured like that, Jinja should be able to interpret a small subset of Mako templates. Jinja
does not support embedded Python code, so you would have to move that out of the template. The syntax for defs
(which are called macros in Jinja) and template inheritance is different too. The following Mako template:
NINE
This part of the documentation shows some tips and tricks for Jinja templates.
Jinja supports dynamic inheritance and does not distinguish between parent and child template as long as no extends tag
is visited. While this leads to the surprising behavior that everything before the first extends tag including whitespace
is printed out instead of being ignored, it can be used for a neat trick.
Usually child templates extend from one template that adds a basic HTML skeleton. However it’s possible to put the
extends tag into an if tag to only extend from the layout template if the standalone variable evaluates to false which it
does per default if it’s not defined. Additionally a very basic skeleton is added to the file so that if it’s indeed rendered
with standalone set to True a very basic HTML skeleton is added:
{% if not standalone %}{% extends 'master.html' %}{% endif -%}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<title>{% block title %}The Page Title{% endblock %}</title>
<link rel="stylesheet" href="style.css" type="text/css">
{% block body %}
<p>This is the page body.</p>
{% endblock %}
If you want to have different styles for each row of a table or list you can use the cycle method on the loop object:
<ul>
{% for row in rows %}
<li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>
{% endfor %}
</ul>
cycle can take an unlimited amount of strings. Each time this tag is encountered the next item from the list is rendered.
Often you want to have a navigation bar with an active navigation item. This is really simple to achieve. Because
assignments outside of blocks in child templates are global and executed before the layout template is evaluated it’s
possible to define the active menu item in the child template:
99
Jinja Documentation (2.11.x), Release 2.11.1
{% extends "layout.html" %}
{% set active_page = "index" %}
The layout template can then access active_page. Additionally it makes sense to define a default for that variable:
{% set navigation_bar = [
('/', 'index', 'Index'),
('/downloads/', 'downloads', 'Downloads'),
('/about/', 'about', 'About')
] -%}
{% set active_page = active_page|default('index') -%}
...
<ul id="navigation">
{% for href, id, caption in navigation_bar %}
<li{% if id == active_page %} class="active"{% endif
%}><a href="{{ href|e }}">{{ caption|e }}</a></li>
{% endfor %}
</ul>
...
The special loop variable always points to the innermost loop. If it’s desired to have access to an outer loop it’s possible
to alias it:
<table>
{% for row in table %}
<tr>
{% set rowloop = loop %}
{% for cell in row %}
<td id="cell-{{ rowloop.index }}-{{ loop.index }}">{{ cell }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
TEN
This page answers some of the often asked questions about Jinja.
The name Jinja was chosen because it’s the name of a Japanese temple and temple and template share a similar
pronunciation. It is not named after the city in Uganda.
We really hate benchmarks especially since they don’t reflect much. The performance of a template depends on many
factors and you would have to benchmark different engines in different situations. The benchmarks from the testsuite
show that Jinja has a similar performance to Mako and is between 10 and 20 times faster than Django’s template
engine or Genshi. These numbers should be taken with tons of salt as the benchmarks that took these numbers only
test a few performance related situations such as looping. Generally speaking the performance of a template engine
doesn’t matter much as the usual bottleneck in a web application is either the database or the application code.
The default syntax of Jinja matches Django syntax in many ways. However this similarity doesn’t mean that you can
use a Django template unmodified in Jinja. For example filter arguments use a function call syntax rather than a colon
to separate filter name and arguments. Additionally the extension interface in Jinja is fundamentally different from the
Django one which means that your custom tags won’t work any longer.
Generally speaking you will use much less custom extensions as the Jinja template system allows you to use a certain
subset of Python expressions which can replace most Django extensions. For example instead of using something like
this:
{% load comments %}
{% get_latest_comments 10 as latest_comments %}
{% for comment in latest_comments %}
...
{% endfor %}
You will most likely provide an object with attributes to retrieve comments from the database:
101
Jinja Documentation (2.11.x), Release 2.11.1
Please keep in mind that even though you may put such things into templates it still isn’t a good idea. Queries should
go into the view code and not the template!
Without a doubt you should try to remove as much logic from templates as possible. But templates without any logic
mean that you have to do all the processing in the code which is boring and stupid. A template engine that does that
is shipped with Python and called string.Template. Comes without loops and if conditions and is by far the fastest
template engine you can get for Python.
So some amount of logic is required in templates to keep everyone happy. And Jinja leaves it pretty much to you how
much logic you want to put into templates. There are some restrictions in what you can do and what not.
Jinja neither allows you to put arbitrary Python code into templates nor does it allow all Python expressions. The oper-
ators are limited to the most common ones and more advanced expressions such as list comprehensions and generator
expressions are not supported. This keeps the template engine easier to maintain and templates more readable.
There are multiple reasons why automatic escaping is not the default mode and also not the recommended one. While
automatic escaping of variables means that you will less likely have an XSS problem it also causes a huge amount of
extra processing in the template engine which can cause serious performance problems. As Python doesn’t provide a
way to mark strings as unsafe Jinja has to hack around that limitation by providing a custom string class (the Markup
string) that safely interacts with safe and unsafe strings.
With explicit escaping however the template engine doesn’t have to perform any safety checks on variables. Also a
human knows not to escape integers or strings that may never contain characters one has to escape or already HTML
markup. For example when iterating over a list over a table of integers and floats for a table of statistics the template
designer can omit the escaping because he knows that integers or floats don’t contain any unsafe parameters.
Additionally Jinja is a general purpose template engine and not only used for HTML/XML generation. For example
you may generate LaTeX, emails, CSS, JavaScript, or configuration files.
When writing a contextfunction() or something similar you may have noticed that the context tries to stop you
from modifying it. If you have managed to modify the context by using an internal context API you may have noticed
that changes in the context don’t seem to be visible in the template. The reason for this is that Jinja uses the context
only as primary data source for template variables for performance reasons.
If you want to modify the context write a function that returns a variable instead that one can assign to a variable by
using set:
If the debugsupport module is not compiled and you are using a Python installation without ctypes (Python 2.4 without
ctypes, Jython or Google’s AppEngine) Jinja is unable to provide correct debugging information and the traceback may
be incomplete. There is currently no good workaround for Jython or the AppEngine as ctypes is unavailable there and
it’s not possible to use the debugsupport extension.
If you are working in the Google AppEngine development server you can whitelist the ctypes module to restore the
tracebacks. This however won’t work in production environments:
import os
if os.environ.get('SERVER_SOFTWARE', '').startswith('Dev'):
from google.appengine.tools.devappserver2.python import sandbox
sandbox._WHITE_LIST_C_MODULES += ['_ctypes', 'gestalt']
Python 2.3 is missing a lot of features that are used heavily in Jinja. This decision was made as with the upcoming
Python 2.6 and 3.0 versions it becomes harder to maintain the code for older Python versions. If you really need
Python 2.3 support you either have to use Jinja 1 or other templating engines that still support 2.3.
Python 2.4/2.5/3.1/3.2 support was removed when we switched to supporting Python 2 and 3 by the same sourcecode
(without using 2to3). It was required to drop support because only Python 2.6/2.7 and >=3.3 support byte and unicode
literals in a way compatible to each other version. If you really need support for older Python 2 (or 3) versions, you
can just use Jinja 2.6.
Python 2.6/3.3 support was dropped because it got dropped in various upstream projects (such as wheel or pytest),
which would make it difficult to continue supporting it. Jinja 2.10 was the last version supporting Python 2.6/3.3.
child.tmpl:
{% extends 'layout.tmpl' %}
{% macro foo() %}CHILD{% endmacro %}
{% block body %}{{ foo() }}{% endblock %}
This will print LAYOUT in Jinja. This is a side effect of having the parent template evaluated after the child one. This
allows child templates passing information to the parent template. To avoid this issue rename the macro or variable in
the parent template to have an uncommon prefix.
ELEVEN
CHANGELOG
11.1 2.11.2
Unreleased
• Fix a bug that caused callable objects with __getattr__, like Mock to be treated as a
contextfunction(). #1145
Released 2020-01-30
• Fix a bug that prevented looking up a key after an attribute ({{ data.items[1:] }}) in an async tem-
plate. #1141
Released 2020-01-27
• Drop support for Python 2.6, 3.3, and 3.4. This will be the last version to support Python 2.7 and 3.5.
• Added a new ChainableUndefined class to support getitem and getattr on an undefined object. #977
• Allow {%+ syntax (with NOP behavior) when lstrip_blocks is disabled. #748
• Added a default parameter for the map filter. #557
• Exclude environment globals from meta.find_undeclared_variables(). #931
• Float literals can be written with scientific notation, like 2.56e-3. #912, #922
• Int and float literals can be written with the ‘_’ separator for legibility, like 12_345. #923
• Fix a bug causing deadlocks in LRUCache.setdefault. #1000
• The trim filter takes an optional string of characters to trim. #828
• A new jinja2.ext.debug extension adds a {% debug %} tag to quickly dump the current context and
available filters and tests. #174, #798#983
• Lexing templates with large amounts of whitespace is much faster. #857, #858
• Parentheses around comparisons are preserved, so {{ 2 * (3 < 5) }} outputs “2” instead of “False”.
#755, #938
105
Jinja Documentation (2.11.x), Release 2.11.1
• Add new boolean, false, true, integer and float tests. #824
• The environment’s finalize function is only applied to the output of expressions (constant or not), not static
template data. #63
• When providing multiple paths to FileSystemLoader, a template can have the same name as a directory.
#821
• Always return Undefined when omitting the else clause in a {{ 'foo' if bar }} expression, regard-
less of the environment’s undefined class. Omitting the else clause is a valid shortcut and should not raise
an error when using StrictUndefined. #710, #1079
• Fix behavior of loop control variables such as length and revindex0 when looping over a generator.
#459#751#794, #993
• Async support is only loaded the first time an environment enables it, in order to avoid a slow initial import.
#765
• In async environments, the |map filter will await the filter call if needed. #913
• In for loops that access loop attributes, the iterator is not advanced ahead of the current iteration unless
length, revindex, nextitem, or last are accessed. This makes it less likely to break groupby re-
sults. #555, #1101
• In async environments, the loop attributes length and revindex work for async iterators. #1101
• In async environments, values from attribute/property access will be awaited if needed. #1101
• PackageLoader doesn’t depend on setuptools or pkg_resources. #970
• PackageLoader has limited support for PEP 420 namespace packages. #1097
• Support os.PathLike objects in FileSystemLoader and ModuleLoader. #870
• NativeTemplate correctly handles quotes between expressions. "'{{ a }}', '{{ b }}'" renders
as the tuple ('1', '2') rather than the string '1, 2'. #1020
• Creating a NativeTemplate directly creates a NativeEnvironment instead of a default
Environment. #1091
• After calling LRUCache.copy(), the copy’s queue methods point to the correct queue. #843
• Compiling templates always writes UTF-8 instead of defaulting to the system encoding. #889
• |wordwrap filter treats existing newlines as separate paragraphs to be wrapped individually, rather than creat-
ing short intermediate lines. #175
• Add break_on_hyphens parameter to |wordwrap filter. #550
• Cython compiled functions decorated as context functions will be passed the context. #1108
• When chained comparisons of constants are evaluated at compile time, the result follows Python’s behavior of
returning False if any comparison returns False, rather than only the last one. #1102
• Tracebacks for exceptions in templates show the correct line numbers and source for Python >= 3.7. #1104
• Tracebacks for template syntax errors in Python 3 no longer show internal compiler frames. #763
• Add a DerivedContextReference node that can be used by extensions to get the current context and
local variables such as loop. #860
• Constant folding during compilation is applied to some node types that were previously overlooked. #733
• TemplateSyntaxError.source is not empty when raised from an included template. #457
• Passing an Undefined value to get_template (such as through extends, import, or include), raises
an UndefinedError consistently. select_template will show the undefined message in the list of
attempts rather than the empty string. #1037
• TemplateSyntaxError can be pickled. #1117
Released 2019-10-04
• Fix a typo in Babel entry point in setup.py that was preventing installation.
Released 2019-10-04
• Fix Python 3.7 deprecation warnings.
• Using range in the sandboxed environment uses xrange on Python 2 to avoid memory use. #933
• Use Python 3.7’s better traceback support to avoid a core dump when using debug builds of Python 3.7. #1050
Released 2019-04-06
• SandboxedEnvironment securely handles str.format_map in order to prevent code execution through
untrusted format strings. The sandbox already handled str.format.
Released 2017-11-08
• Added a new extension node called OverlayScope which can be used to create an unoptimized scope that
will look up all variables from a derived context.
• Added an in test that works like the in operator. This can be used in combination with reject and select.
• Added previtem and nextitem to loop contexts, providing access to the previous/next item in the loop. If
such an item does not exist, the value is undefined.
• Added changed(*values) to loop contexts, providing an easy way of checking whether a value has changed
since the last iteration (or rather since the last call of the method)
• Added a namespace function that creates a special object which allows attribute assignment using the set
tag. This can be used to carry data across scopes, e.g. from a loop body to code that comes after the loop.
• Added a trimmed modifier to {% trans %} to strip linebreaks and surrounding whitespace. Also added a
new policy to enable this for all trans blocks.
• The random filter is no longer incorrectly constant folded and will produce a new random choice each time the
template is rendered. #478
• Added a unique filter. #469
Released 2017-04-03
• Fixed custom context behavior in fast resolve mode #675
Released 2017-01-28
• Restored the original repr of the internal _GroupTuple because this caused issues with ansible and it was an
unintended change. #654
• Added back support for custom contexts that override the old resolve method since it was hard for people to
spot that this could cause a regression.
• Correctly use the buffer for the else block of for loops. This caused invalid syntax errors to be caused on 2.x and
completely wrong behavior on Python 3 #669
• Resolve an issue where the {% extends %} tag could not be used with async environments. #668
• Reduce memory footprint slightly by reducing our unicode database dump we use for identifier matching on
Python 3 #666
• Fixed autoescaping not working for macros in async compilation mode. #671
Released 2017-01-10
• Solved some warnings for string literals. #646
• Increment the bytecode cache version which was not done due to an oversight before.
• Corrected bad code generation and scoping for filtered loops. #649
• Resolved an issue where top-level output silencing after known extend blocks could generate invalid code when
blocks where contained in if statements. #651
• Made the truncate.leeway default configurable to improve compatibility with older templates.
Released 2017-01-08
• Restored the use of blocks in macros to the extend that was possible before. On Python 3 it would render a
generator repr instead of the block contents. #645
• Set a consistent behavior for assigning of variables in inner scopes when the variable is also read from an outer
scope. This now sets the intended behavior in all situations however it does not restore the old behavior where
limited assignments to outer scopes was possible. For more information and a discussion see #641
• Resolved an issue where block scoped would not take advantage of the new scoping rules. In some more
exotic cases a variable overriden in a local scope would not make it into a block.
• Change the code generation of the with statement to be in line with the new scoping rules. This resolves some
unlikely bugs in edge cases. This also introduces a new internal With node that can be used by extensions.
Released 2017-01-08
• Fixed a regression that caused for loops to not be able to use the same variable for the target as well as source
iterator. #640
• Add support for a previously unknown behavior of macros. It used to be possible in some circumstances to
explicitly provide a caller argument to macros. While badly buggy and unintended it turns out that this is a
common case that gets copy pasted around. To not completely break backwards compatibility with the most
common cases it’s now possible to provide an explicit keyword argument for caller if it’s given an explicit
default. #642
Released 2017-01-07
• Resolved a regression with call block scoping for macros. Nested caller blocks that used the same identifiers as
outer macros could refer to the wrong variable incorrectly.
Released 2016-12-29
• Fixed the for_qs flag for urlencode.
• Fixed regression when applying int to non-string values.
• SECURITY: if the sandbox mode is used format expressions are now sandboxed with the same rules as in Jinja.
This solves various information leakage problems that can occur with format strings.
• Changed cache keys to use absolute file names if available instead of load names.
• Fixed loop length calculation for some iterators.
• Changed how Jinja enforces strings to be native strings in Python 2 to work when people break their default
encoding.
• Added make_logging_undefined which returns an undefined object that logs failures into a logger.
• If unmarshalling of cached data fails the template will be reloaded now.
• Implemented a block set tag.
• Default cache size was increased to 400 from a low 50.
• Fixed is number test to accept long integers in all Python versions.
• Changed is number to accept Decimal as a number.
• Added a check for default arguments followed by non-default arguments. This change makes {% macro
m(x, y=1, z) %} a syntax error. The previous behavior for this code was broken anyway (resulting in the
default value being applied to y).
• Add ability to use custom subclasses of jinja2.compiler.CodeGenerator and jinja2.
runtime.Context by adding two new attributes to the environment (code_generator_class and
context_class). #404
• Added support for context/environment/evalctx decorator functions on the finalize callback of the environment.
• Escape query strings for urlencode properly. Previously slashes were not escaped in that place.
• Add ‘base’ parameter to ‘int’ filter.
Released 2014-06-06
• Security issue: Corrected the security fix for the cache folder. This fix was provided by RedHat.
Released 2014-01-10
• Prefix loader was not forwarding the locals properly to inner loaders. This is now fixed.
• Security issue: Changed the default folder for the filesystem cache to be user specific and read and write pro-
tected on UNIX systems. See Debian bug 734747 for more information.
Released 2013-08-07
• Fixed a bug with call_filter not working properly on environment and context filters.
• Fixed lack of Python 3 support for bytecode caches.
• Reverted support for defining blocks in included templates as this broke existing templates for users.
• Fixed some warnings with hashing of undefineds and nodes if Python is run with warnings for Python 3.
• Automatically detect newer Python interpreter versions before loading code from bytecode caches to prevent
segfaults on invalid opcodes. The segfault in earlier Jinja versions here was not a Jinja bug but a limitation in the
underlying Python interpreter. If you notice Jinja segfaulting in earlier versions after an upgrade of the Python
interpreter you don’t have to upgrade, it’s enough to flush the bytecode cache. This just no longer makes this
necessary, Jinja will automatically detect these cases now.
• The sum filter can now sum up values by attribute. This is a backwards incompatible change. The argument
to the filter previously was the optional starting index which defaults to zero. This now became the second
argument to the function because it’s rarely used.
• Like sum, sort now also makes it possible to order items by attribute.
• Like sum and sort, join now also is able to join attributes of objects as string.
• The internal eval context now has a reference to the environment.
• Added a mapping test to see if an object is a dict or an object with a similar interface.
Released 2010-10-18
• Built documentation is no longer part of release.
Released 2010-10-17
• Fixed extensions not loading properly with overlays.
• Work around a bug in cpython for the debugger that causes segfaults on 64bit big-endian architectures.
Released 2010-10-17
• Fixed an operator precedence error introduced in 2.5.2. Statements like “-foo.bar” had their implicit parentheses
applied around the first part of the expression (“(-foo).bar”) instead of the more correct “-(foo.bar)”.
Released 2010-08-18
• Improved setup.py script to better work with assumptions people might still have from it
(--with-speedups).
• Fixed a packaging error that excluded the new debug support.
Released 2010-08-17
• StopIteration exceptions raised by functions called from templates are now intercepted and converted to unde-
fineds. This solves a lot of debugging grief. (StopIteration is used internally to abort template execution)
• Improved performance of macro calls slightly.
• Babel extraction can now properly extract newstyle gettext calls.
• Using the variable num in newstyle gettext for something else than the pluralize count will no longer raise a
KeyError.
• Removed builtin markup class and switched to markupsafe. For backwards compatibility the pure Python im-
plementation still exists but is pulled from markupsafe by the Jinja developers. The debug support went into a
separate feature called “debugsupport” and is disabled by default because it is only relevant for Python 2.4
• Fixed an issue with unary operators having the wrong precedence.
Released 2010-04-20
• Fixed an error reporting bug for undefined.
Released 2010-02-19
• Fixed an error reporting bug on all python versions
• Fixed an error reporting bug on Python 2.4
Released 2009-09-14
• Fixes some smaller problems for Jinja on Jython.
Released 2008-12-25
• Fixed a translation error caused by looping over empty recursive loops.
Released 2008-06-09
• First release of Jinja 2.
• genindex
• search
j
jinja2.ext, 78
jinja2.nativetypes, 34
jinja2.nodes, 84
jinja2.sandbox, 31
119
Jinja Documentation (2.11.x), Release 2.11.1
121
Jinja Documentation (2.11.x), Release 2.11.1
default_unop_table F
(jinja2.sandbox.SandboxedEnvironment at- fail() (jinja2.parser.Parser method), 82
tribute), 31 false() (built-in function), 67
defined() (built-in function), 66 filename (jinja2.parser.Parser attribute), 82
DerivedContextReference (class in jinja2.nodes), filename (jinja2.Template attribute), 11
86 filename (jinja2.TemplateSyntaxError attribute), 25
Dict (class in jinja2.nodes), 87 filesizeformat() (built-in function), 58
dict() (built-in function), 69 FileSystemBytecodeCache (class in jinja2), 21
DictLoader (class in jinja2), 18 FileSystemLoader (class in jinja2), 18
dictsort() (built-in function), 58 Filter (class in jinja2.nodes), 86
disable_buffering() filter_stream() (jinja2.ext.Extension method), 81
(jinja2.environment.TemplateStream method), FilterBlock (class in jinja2.nodes), 90
12 filters (jinja2.Environment attribute), 8
Div (class in jinja2.nodes), 85 find() (jinja2.nodes.Node method), 84
divisibleby() (built-in function), 67 find_all() (jinja2.nodes.Node method), 84
dump() (jinja2.environment.TemplateStream method), find_referenced_templates() (in module
12 jinja2.meta), 29
dump_bytecode() (jinja2.BytecodeCache method), find_undeclared_variables() (in module
20 jinja2.meta), 29
first() (built-in function), 58
E float() (built-in function), 58, 67
enable_buffering() FloorDiv (class in jinja2.nodes), 85
(jinja2.environment.TemplateStream method), For (class in jinja2.nodes), 90
12 forceescape() (built-in function), 58
Environment (class in jinja2), 6 format() (built-in function), 58
environment (jinja2.bccache.Bucket attribute), 20 free_identifier() (jinja2.parser.Parser method),
environment (jinja2.runtime.Context attribute), 16 82
EnvironmentAttribute (class in jinja2.nodes), 86 from_string() (jinja2.Environment method), 10
environmentfilter() (in module jinja2), 23 FromImport (class in jinja2.nodes), 90
environmentfunction() (in module jinja2), 23 FunctionLoader (class in jinja2), 19
eos() (jinja2.lexer.TokenStream property), 83
eq() (built-in function), 67 G
escape() (built-in function), 58 ge() (built-in function), 67
escape() (in module jinja2), 23 generate() (jinja2.Template method), 11
escape() (jinja2.Markup class method), 24 generate_async() (jinja2.Template method), 12
escaped() (built-in function), 67 get() (jinja2.MemcachedBytecodeCache.MinimalClientInterface
eval_ctx (jinja2.runtime.Context attribute), 16 method), 21
EvalContext (class in jinja2.nodes), 27 get_all() (jinja2.runtime.Context method), 17
evalcontextfilter() (in module jinja2), 23 get_exported() (jinja2.runtime.Context method), 17
evalcontextfunction() (in module jinja2), 23 get_or_select_template() (jinja2.Environment
EvalContextModifier (class in jinja2.nodes), 89 method), 10
even() (built-in function), 67 get_source() (jinja2.BaseLoader method), 17
expect() (jinja2.lexer.TokenStream method), 83 get_template() (jinja2.Environment method), 10
exported_vars (jinja2.runtime.Context attribute), 16 Getattr (class in jinja2.nodes), 87
Expr (class in jinja2.nodes), 85 Getitem (class in jinja2.nodes), 87
ExprStmt (class in jinja2.nodes), 89 globals (jinja2.Environment attribute), 8
extend() (jinja2.Environment method), 10 globals (jinja2.Template attribute), 11
Extends (class in jinja2.nodes), 90 groupby() (built-in function), 59
Extension (class in jinja2.ext), 81 gt() (built-in function), 67
ExtensionAttribute (class in jinja2.nodes), 86
extract_translations() (jinja2.Environment H
method), 76
Helper (class in jinja2.nodes), 88
122 Index
Jinja Documentation (2.11.x), Release 2.11.1
I L
identifier (jinja2.ext.Extension attribute), 81 last() (built-in function), 60
If (class in jinja2.nodes), 90 le() (built-in function), 67
ImmutableSandboxedEnvironment (class in length() (built-in function), 60
jinja2.sandbox), 32 lex() (jinja2.Environment method), 28
Import (class in jinja2.nodes), 90 lineno (jinja2.lexer.Token attribute), 83
ImportedName (class in jinja2.nodes), 87 lineno (jinja2.TemplateSyntaxError attribute), 25
Impossible, 91 lipsum() (built-in function), 69
in() (built-in function), 67 List (class in jinja2.nodes), 87
Include (class in jinja2.nodes), 90 list() (built-in function), 60
indent() (built-in function), 59 list_templates() (jinja2.Environment method), 10
install_gettext_callables() Literal (class in jinja2.nodes), 87
(jinja2.Environment method), 75 load() (jinja2.BaseLoader method), 18
install_gettext_translations() load_bytecode() (jinja2.bccache.Bucket method),
(jinja2.Environment method), 75 21
install_null_translations() load_bytecode() (jinja2.BytecodeCache method),
(jinja2.Environment method), 75 20
int() (built-in function), 59 look() (jinja2.lexer.TokenStream method), 83
integer() (built-in function), 67 lower() (built-in function), 60, 67
intercepted_binops lt() (built-in function), 67
(jinja2.sandbox.SandboxedEnvironment at-
tribute), 31 M
intercepted_unops Macro (class in jinja2.nodes), 90
(jinja2.sandbox.SandboxedEnvironment at- make_logging_undefined() (in module jinja2),
tribute), 32 15
InternalName (class in jinja2.nodes), 87 make_module() (jinja2.Template method), 12
is_internal_attribute() (in module map() (built-in function), 60
jinja2.sandbox), 32 mapping() (built-in function), 68
is_safe_attribute() MarkSafe (class in jinja2.nodes), 87
(jinja2.sandbox.SandboxedEnvironment MarkSafeIfAutoescape (class in jinja2.nodes), 88
method), 32 Markup (class in jinja2), 24
is_safe_callable() max() (built-in function), 60
(jinja2.sandbox.SandboxedEnvironment MemcachedBytecodeCache (class in jinja2), 21
method), 32 MemcachedBytecodeCache.MinimalClientInterface
is_undefined() (in module jinja2), 24 (class in jinja2), 21
is_up_to_date (jinja2.Template attribute), 29 message (jinja2.TemplateSyntaxError attribute), 25
iter_child_nodes() (jinja2.nodes.Node method), min() (built-in function), 61
84 Mod (class in jinja2.nodes), 85
iter_fields() (jinja2.nodes.Node method), 84 modifies_known_mutable() (in module
iterable() (built-in function), 67 jinja2.sandbox), 32
module() (jinja2.Template property), 12
J ModuleLoader (class in jinja2), 19
jinja2.ext (module), 78 Mul (class in jinja2.nodes), 85
jinja2.nativetypes (module), 34
jinja2.nodes (module), 84 N
jinja2.sandbox (module), 31 Name (class in jinja2.nodes), 88
join() (built-in function), 59 name (jinja2.parser.Parser attribute), 82
join_path() (jinja2.Environment method), 10 name (jinja2.runtime.Context attribute), 16
joiner (built-in class), 69 name (jinja2.Template attribute), 11
name (jinja2.TemplateSyntaxError attribute), 25
K namespace (built-in class), 70
key (jinja2.bccache.Bucket attribute), 20 NativeEnvironment (class in jinja2.nativetypes), 36
Keyword (class in jinja2.nodes), 88 NativeTemplate (class in jinja2.nativetypes), 36
Index 123
Jinja Documentation (2.11.x), Release 2.11.1
R T
random() (built-in function), 61 tags (jinja2.ext.Extension attribute), 81
range() (built-in function), 68 Template (class in jinja2), 11
reject() (built-in function), 61 Template (class in jinja2.nodes), 91
rejectattr() (built-in function), 61 TemplateAssertionError, 25
render() (jinja2.nativetypes.NativeTemplate method), TemplateData (class in jinja2.nodes), 87
36 TemplateError, 25
render() (jinja2.Template method), 11 TemplateNotFound, 25
render_async() (jinja2.Template method), 11 TemplateRuntimeError, 25
replace() (built-in function), 61 TemplatesNotFound, 25
124 Index
Jinja Documentation (2.11.x), Release 2.11.1
U
UnaryExpr (class in jinja2.nodes), 88
Undefined (class in jinja2), 14
undefined() (built-in function), 68
undefined() (jinja2.Environment method), 8
UndefinedError, 25
unescape() (jinja2.Markup method), 24
uninstall_gettext_translations()
(jinja2.Environment method), 76
unique() (built-in function), 65
unsafe() (in module jinja2.sandbox), 32
upper() (built-in function), 65, 68
urlencode() (built-in function), 65
urlize() (built-in function), 65
V
value (jinja2.lexer.Token attribute), 83
vars (jinja2.runtime.Context attribute), 16
volatile (jinja2.nodes.EvalContext attribute), 27
W
With (class in jinja2.nodes), 91
wordcount() (built-in function), 65
wordwrap() (built-in function), 65
write_bytecode() (jinja2.bccache.Bucket method),
21
X
xmlattr() (built-in function), 66
Index 125