Skip to content
Myr

api.rst

This file

Path

docs/api.rst

935 lines · 32.2 KiB

Last changed by

Merge pull request #1161 from ldealmei/patch-1David Lordbefore adoptioneccf9a0

History of this file

Take it

The walk stopped after 200 commits: lines older than 793ddd4 point at it.

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 1–3why, one step back
1API
2===3

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 4why, one step back
4.. module:: jinja2

Merge pull request #1015 from jab/pr-1011Joshua Bronsonbefore adoption7798e79

line 5why, one step back
5 :noindex:

Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205

line 6why, one step back
6 :synopsis: public Jinja API

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 7why, one step back
7

Merge pull request #1161 from ldealmei/patch-1David Lordbefore adoptioneccf9a0

lines 8–11why, one step back
8This document describes the API to Jinja and not the template language
9(for that, see :doc:`/templates`). It will be most useful as reference10to those implementing the template interface to the application and not11those who are creating Jinja templates.

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 12–15why, one step back
12
13Basics14------15

Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205

line 16why, one step back
16Jinja uses a central object called the template :class:`Environment`.

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 17–23why, one step back
17Instances of this class are used to store the configuration and global objects,
18and are used to load templates from the file system or other locations.19Even if you are creating templates from strings by using the constructor of20:class:`Template` class, an environment is created automatically for you,21albeit a shared one.2223Most applications will create one :class:`Environment` object on application

Merge pull request #891 from jdufresne/wsDavid Lordbefore adoptionf9bb207

line 24why, one step back
24initialization and use that to load templates. In some cases however, it's

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 25–27why, one step back
25useful to have multiple environments side by side, if different configurations
26are in use.27

Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205

line 28why, one step back
28The simplest way to configure Jinja to load templates for your application

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 29–30why, one step back
29looks roughly like this::
30

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 31why, one step back
31 from jinja2 import Environment, PackageLoader, select_autoescape

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 32–50why, one step back
32 env = Environment(
33 loader=PackageLoader('yourapplication', 'templates'),34 autoescape=select_autoescape(['html', 'xml'])35 )3637This will create a template environment with the default settings and a38loader that looks up the templates in the `templates` folder inside the39`yourapplication` python package. Different loaders are available40and you can also write your own if you want to load templates from a41database or other resources. This also enables autoescaping for HTML and42XML files.4344To load a template from this environment you just have to call the45:meth:`get_template` method which then returns the loaded :class:`Template`::4647 template = env.get_template('mytemplate.html')4849To render it with some variables, just call the :meth:`render` method::50

Merge branch '2.10.x'David Lordbefore adoption13cc9f4

line 51why, one step back
51 print(template.render(the='variables', go='here'))

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 52–58why, one step back
52
53Using a template loader rather than passing strings to :class:`Template`54or :meth:`Environment.from_string` has multiple advantages. Besides being55a lot easier to use it also enables template inheritance.5657.. admonition:: Notes on Autoescaping58

Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205

line 59why, one step back
59 In future versions of Jinja we might enable autoescaping by default

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 60–66why, one step back
60 for security reasons. As such you are encouraged to explicitly
61 configure autoescaping now instead of relying on the default.626364Unicode65-------66

Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205

line 67why, one step back
67Jinja is using Unicode internally which means that you have to pass Unicode

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 68–91why, one step back
68objects to the render function or bytestrings that only consist of ASCII
69characters. Additionally newlines are normalized to one end of line70sequence which is per default UNIX style (``\n``).7172Python 2.x supports two ways of representing string objects. One is the73`str` type and the other is the `unicode` type, both of which extend a type74called `basestring`. Unfortunately the default is `str` which should not75be used to store text based information unless only ASCII characters are76used. With Python 2.6 it is possible to make `unicode` the default on a per77module level and with Python 3 it will be the default.7879To explicitly use a Unicode string you have to prefix the string literal80with a `u`: ``u'Hänsel und Gretel sagen Hallo'``. That way Python will81store the string as Unicode by decoding the string with the character82encoding from the current Python module. If no encoding is specified this83defaults to 'ASCII' which means that you can't use any non ASCII identifier.8485To set a better module encoding add the following comment to the first or86second line of the Python module using the Unicode literal::8788 # -*- coding: utf-8 -*-8990We recommend utf-8 as Encoding for Python modules and templates as it's91possible to represent every Unicode character in utf-8 and because it's

Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205

line 92why, one step back
92backwards compatible to ASCII. For Jinja the default encoding of templates

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 93–94why, one step back
93is assumed to be utf-8.
94

Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205

lines 95–97why, one step back
95It is not possible to use Jinja to process non-Unicode data. The reason
96for this is that Jinja uses Unicode already on the language level. For97example Jinja treats the non-breaking space as valid whitespace inside

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 98–103why, one step back
98expressions which requires knowledge of the encoding or operating on an
99Unicode string.100101For more details about Unicode in Python have a look at the excellent102`Unicode documentation`_.103

Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205

line 104why, one step back
104Another important thing is how Jinja is handling string literals in

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 105–108why, one step back
105templates. A naive implementation would be using Unicode strings for
106all string literals but it turned out in the past that this is problematic107as some libraries are typechecking against `str` explicitly. For example108`datetime.strftime` does not accept Unicode arguments. To not break it

Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205

line 109why, one step back
109completely Jinja is returning `str` for strings that fit into ASCII and

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 110–118why, one step back
110for everything else `unicode`:
111112>>> m = Template(u"{% set a, b = 'foo', 'föö' %}").module113>>> m.a114'foo'115>>> m.b116u'f\xf6\xf6'117118

Merge branch '2.10.x'David Lordbefore adoption9550dc8

line 119why, one step back
119.. _Unicode documentation: https://docs.python.org/3/howto/unicode.html

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 120–124why, one step back
120
121High Level API122--------------123124The high-level API is the API you will use in the application to load and

Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205

lines 125–126why, one step back
125render Jinja templates. The :ref:`low-level-api` on the other side is only
126useful if you want to dig deeper into Jinja or :ref:`develop extensions

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 127–145why, one step back
127<jinja-extensions>`.
128129.. autoclass:: Environment([options])130 :members: from_string, get_template, select_template,131 get_or_select_template, join_path, extend, compile_expression,132 compile_templates, list_templates, add_extension133134 .. attribute:: shared135136 If a template was created by using the :class:`Template` constructor137 an environment is created automatically. These environments are138 created as shared environments which means that multiple templates139 may have the same anonymous environment. For all shared environments140 this attribute is `True`, else `False`.141142 .. attribute:: sandboxed143144 If the environment is sandboxed this attribute is `True`. For the145 sandbox mode have a look at the documentation for the

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 146why, one step back
146 :class:`~jinja2.sandbox.SandboxedEnvironment`.

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 147–185why, one step back
147
148 .. attribute:: filters149150 A dict of filters for this environment. As long as no template was151 loaded it's safe to add new filters or remove old. For custom filters152 see :ref:`writing-filters`. For valid filter names have a look at153 :ref:`identifier-naming`.154155 .. attribute:: tests156157 A dict of test functions for this environment. As long as no158 template was loaded it's safe to modify this dict. For custom tests159 see :ref:`writing-tests`. For valid test names have a look at160 :ref:`identifier-naming`.161162 .. attribute:: globals163164 A dict of global variables. These variables are always available165 in a template. As long as no template was loaded it's safe166 to modify this dict. For more details see :ref:`global-namespace`.167 For valid object names have a look at :ref:`identifier-naming`.168169 .. attribute:: policies170171 A dictionary with :ref:`policies`. These can be reconfigured to172 change the runtime behavior or certain template features. Usually173 these are security related.174175 .. attribute:: code_generator_class176177 The class used for code generation. This should not be changed178 in most cases, unless you need to modify the Python code a179 template compiles to.180181 .. attribute:: context_class182183 The context used for templates. This should not be changed184 in most cases, unless you need to modify internals of how185 template variables are handled. For details, see

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 186why, one step back
186 :class:`~jinja2.runtime.Context`.

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 187–217why, one step back
187
188 .. automethod:: overlay([options])189190 .. method:: undefined([hint, obj, name, exc])191192 Creates a new :class:`Undefined` object for `name`. This is useful193 for filters or functions that may return undefined objects for194 some operations. All parameters except of `hint` should be provided195 as keyword parameters for better readability. The `hint` is used as196 error message for the exception if provided, otherwise the error197 message will be generated from `obj` and `name` automatically. The exception198 provided as `exc` is raised if something with the generated undefined199 object is done that the undefined object does not allow. The default200 exception is :exc:`UndefinedError`. If a `hint` is provided the201 `name` may be omitted.202203 The most common way to create an undefined object is by providing204 a name only::205206 return environment.undefined(name='some_name')207208 This means that the name `some_name` is not defined. If the name209 was from an attribute of an object it makes sense to tell the210 undefined object the holder object to improve the error message::211212 if not hasattr(obj, 'attr'):213 return environment.undefined(obj=obj, name='attr')214215 For a more complex example you can provide a hint. For example216 the :func:`first` filter creates an undefined object that way::217

Merge pull request #891 from jdufresne/wsDavid Lordbefore adoptionf9bb207

line 218why, one step back
218 return environment.undefined('no first item, sequence was empty')

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 219–254why, one step back
219
220 If it the `name` or `obj` is known (for example because an attribute221 was accessed) it should be passed to the undefined object, even if222 a custom `hint` is provided. This gives undefined objects the223 possibility to enhance the error message.224225.. autoclass:: Template226 :members: module, make_module227228 .. attribute:: globals229230 The dict with the globals of that template. It's unsafe to modify231 this dict as it may be shared with other templates or the environment232 that loaded the template.233234 .. attribute:: name235236 The loading name of the template. If the template was loaded from a237 string this is `None`.238239 .. attribute:: filename240241 The filename of the template on the file system if it was loaded from242 there. Otherwise this is `None`.243244 .. automethod:: render([context])245246 .. automethod:: generate([context])247248 .. automethod:: stream([context])249250 .. automethod:: render_async([context])251252 .. automethod:: generate_async([context])253254

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 255why, one step back
255.. autoclass:: jinja2.environment.TemplateStream()

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 256–263why, one step back
256 :members: disable_buffering, enable_buffering, dump
257258259Autoescaping260------------261262.. versionchanged:: 2.4263

Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205

line 264why, one step back
264Jinja now comes with autoescaping support. As of Jinja 2.9 the

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 265–270why, one step back
265autoescape extension is removed and built-in. However autoescaping is
266not yet enabled by default though this will most likely change in the267future. It's recommended to configure a sensible default for268autoescaping. This makes it possible to enable and disable autoescaping269on a per-template basis (HTML versus text for instance).270

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 271why, one step back
271.. autofunction:: jinja2.select_autoescape

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 272–274why, one step back
272
273Here a recommended setup that enables autoescaping for templates ending274in ``'.html'``, ``'.htm'`` and ``'.xml'`` and disabling it by default

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 275why, one step back
275for all other extensions. You can use the :func:`~jinja2.select_autoescape`

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 276–277why, one step back
276function for this::
277

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 278why, one step back
278 from jinja2 import Environment, select_autoescape

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 279–282why, one step back
279 env = Environment(autoescape=select_autoescape(['html', 'htm', 'xml']),
280 loader=PackageLoader('mypackage'))281282The :func:`~jinja.select_autoescape` function returns a function that

Merge pull request #783 from luzpaz/trivial-typosDavid Lordbefore adoption9b255f4

line 283why, one step back
283works roughly like this::

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 284–303why, one step back
284
285 def autoescape(template_name):286 if template_name is None:287 return False288 if template_name.endswith(('.html', '.htm', '.xml'))289290When implementing a guessing autoescape function, make sure you also291accept `None` as valid template name. This will be passed when generating292templates from strings. You should always configure autoescaping as293defaults in the future might change.294295Inside the templates the behaviour can be temporarily changed by using296the `autoescape` block (see :ref:`autoescape-overrides`).297298299.. _identifier-naming:300301Notes on Identifiers302--------------------303

Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205

lines 304–305why, one step back
304Jinja uses Python naming rules. Valid identifiers can be any combination
305of Unicode characters accepted by Python.

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 306–324why, one step back
306
307Filters and tests are looked up in separate namespaces and have slightly308modified identifier syntax. Filters and tests may contain dots to group309filters and tests by topic. For example it's perfectly valid to add a310function into the filter dict and call it `to.unicode`. The regular311expression for filter and test identifiers is312``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.313314315Undefined Types316---------------317318These classes can be used as undefined types. The :class:`Environment`319constructor takes an `undefined` parameter that can be one of those classes320or a custom subclass of :class:`Undefined`. Whenever the template engine is321unable to look up a name or access an attribute one of those objects is322created and returned. Some operations on undefined values are then allowed,323others fail.324

Add ChainableUndefined allowing getattr & getitem (#997)Étienne Pelletierbefore adoption19133d4

line 325why, one step back
325The closest to regular Python behavior is the :class:`StrictUndefined` which

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 326–327why, one step back
326disallows all operations beside testing if it's an undefined object.
327

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 328why, one step back
328.. autoclass:: jinja2.Undefined()

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 329–354why, one step back
329
330 .. attribute:: _undefined_hint331332 Either `None` or an unicode string with the error message for333 the undefined object.334335 .. attribute:: _undefined_obj336337 Either `None` or the owner object that caused the undefined object338 to be created (for example because an attribute does not exist).339340 .. attribute:: _undefined_name341342 The name for the undefined variable / attribute or just `None`343 if no such information exists.344345 .. attribute:: _undefined_exception346347 The exception that the undefined object wants to raise. This348 is usually one of :exc:`UndefinedError` or :exc:`SecurityError`.349350 .. method:: _fail_with_undefined_error(\*args, \**kwargs)351352 When called with any arguments this method raises353 :attr:`_undefined_exception` with an error message generated354 from the undefined hints stored on the undefined object.

Add ChainableUndefined allowing getattr & getitem (#997)Étienne Pelletierbefore adoption19133d4

line 355why, one step back
355

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 356why, one step back
356.. autoclass:: jinja2.ChainableUndefined()

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 357why, one step back
357

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 358why, one step back
358.. autoclass:: jinja2.DebugUndefined()

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 359why, one step back
359

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 360why, one step back
360.. autoclass:: jinja2.StrictUndefined()

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 361–364why, one step back
361
362There is also a factory function that can decorate undefined objects to363implement logging on failures:364

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 365why, one step back
365.. autofunction:: jinja2.make_logging_undefined

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 366–384why, one step back
366
367Undefined objects are created by calling :attr:`undefined`.368369.. admonition:: Implementation370371 :class:`Undefined` objects are implemented by overriding the special372 `__underscore__` methods. For example the default :class:`Undefined`373 class implements `__unicode__` in a way that it returns an empty374 string, however `__int__` and others still fail with an exception. To375 allow conversion to int by returning ``0`` you can implement your own::376377 class NullUndefined(Undefined):378 def __int__(self):379 return 0380 def __float__(self):381 return 0.0382383 To disallow a method, just override it and raise384 :attr:`~Undefined._undefined_exception`. Because this is a very common

Merge pull request #943 from RubenGarcia/masterDavid Lordbefore adoption6e08416

line 385why, one step back
385 idiom in undefined objects there is the helper method

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 386–396why, one step back
386 :meth:`~Undefined._fail_with_undefined_error` that does the error raising
387 automatically. Here a class that works like the regular :class:`Undefined`388 but chokes on iteration::389390 class NonIterableUndefined(Undefined):391 __iter__ = Undefined._fail_with_undefined_error392393394The Context395-----------396

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 397why, one step back
397.. autoclass:: jinja2.runtime.Context()

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 398–440why, one step back
398 :members: resolve, get_exported, get_all
399400 .. attribute:: parent401402 A dict of read only, global variables the template looks up. These403 can either come from another :class:`Context`, from the404 :attr:`Environment.globals` or :attr:`Template.globals` or points405 to a dict created by combining the globals with the variables406 passed to the render function. It must not be altered.407408 .. attribute:: vars409410 The template local variables. This list contains environment and411 context functions from the :attr:`parent` scope as well as local412 modifications and exported variables from the template. The template413 will modify this dict during template evaluation but filters and414 context functions are not allowed to modify it.415416 .. attribute:: environment417418 The environment that loaded the template.419420 .. attribute:: exported_vars421422 This set contains all the names the template exports. The values for423 the names are in the :attr:`vars` dict. In order to get a copy of the424 exported variables as dict, :meth:`get_exported` can be used.425426 .. attribute:: name427428 The load name of the template owning this context.429430 .. attribute:: blocks431432 A dict with the current mapping of blocks in the template. The keys433 in this dict are the names of the blocks, and the values a list of434 blocks registered. The last item in each list is the current active435 block (latest in the inheritance chain).436437 .. attribute:: eval_ctx438439 The current :ref:`eval-context`.440

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 441why, one step back
441 .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs)

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 442–446why, one step back
442
443444.. admonition:: Implementation445446 Context is immutable for the same reason Python's frame locals are

Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205

line 447why, one step back
447 immutable inside functions. Both Jinja and Python are not using the

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 448–450why, one step back
448 context / frame locals as data storage for variables but only as primary
449 data source.450

Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205

line 451why, one step back
451 When a template accesses a variable the template does not define, Jinja

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 452–467why, one step back
452 looks up the variable in the context, after that the variable is treated
453 as if it was defined in the template.454455456.. _loaders:457458Loaders459-------460461Loaders are responsible for loading templates from a resource such as the462file system. The environment will keep the compiled modules in memory like463Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in464size by default and templates are automatically reloaded.465All loaders are subclasses of :class:`BaseLoader`. If you want to create your466own loader, subclass :class:`BaseLoader` and override `get_source`.467

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 468why, one step back
468.. autoclass:: jinja2.BaseLoader

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 469–470why, one step back
469 :members: get_source, load
470

Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205

line 471why, one step back
471Here a list of the builtin loaders Jinja provides:

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 472why, one step back
472

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 473why, one step back
473.. autoclass:: jinja2.FileSystemLoader

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 474why, one step back
474

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 475why, one step back
475.. autoclass:: jinja2.PackageLoader

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 476why, one step back
476

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 477why, one step back
477.. autoclass:: jinja2.DictLoader

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 478why, one step back
478

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 479why, one step back
479.. autoclass:: jinja2.FunctionLoader

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 480why, one step back
480

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 481why, one step back
481.. autoclass:: jinja2.PrefixLoader

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 482why, one step back
482

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 483why, one step back
483.. autoclass:: jinja2.ChoiceLoader

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 484why, one step back
484

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 485why, one step back
485.. autoclass:: jinja2.ModuleLoader

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 486–502why, one step back
486
487488.. _bytecode-cache:489490Bytecode Cache491--------------492493Jinja 2.1 and higher support external bytecode caching. Bytecode caches make494it possible to store the generated bytecode on the file system or a different495location to avoid parsing the templates on first use.496497This is especially useful if you have a web application that is initialized on498the first request and Jinja compiles many templates at once which slows down499the application.500501To use a bytecode cache, instantiate it and pass it to the :class:`Environment`.502

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 503why, one step back
503.. autoclass:: jinja2.BytecodeCache

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 504–505why, one step back
504 :members: load_bytecode, dump_bytecode, clear
505

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 506why, one step back
506.. autoclass:: jinja2.bccache.Bucket

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 507–524why, one step back
507 :members: write_bytecode, load_bytecode, bytecode_from_string,
508 bytecode_to_string, reset509510 .. attribute:: environment511512 The :class:`Environment` that created the bucket.513514 .. attribute:: key515516 The unique cache key for this bucket517518 .. attribute:: code519520 The bytecode if it's loaded, otherwise `None`.521522523Builtin bytecode caches:524

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 525why, one step back
525.. autoclass:: jinja2.FileSystemBytecodeCache

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 526why, one step back
526

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 527why, one step back
527.. autoclass:: jinja2.MemcachedBytecodeCache

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 528–532why, one step back
528
529530Async Support531-------------532

Merge pull request #1149 from davidbrochart/fix_docDavid Lordbefore adoption2a70ef2

line 533why, one step back
533.. versionadded:: 2.9

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 534why, one step back
534

Merge pull request #1149 from davidbrochart/fix_docDavid Lordbefore adoption2a70ef2

lines 535–539why, one step back
535Jinja supports the Python ``async`` and ``await`` syntax. For the
536template designer, this support (when enabled) is entirely transparent,537templates continue to look exactly the same. However, developers should538be aware of the implementation as it affects what types of APIs you can539use.

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 540why, one step back
540

Merge pull request #1149 from davidbrochart/fix_docDavid Lordbefore adoption2a70ef2

lines 541–544why, one step back
541By default, async support is disabled. Enabling it will cause the
542environment to compile different code behind the scenes in order to543handle async and sync code in an asyncio event loop. This has the544following implications:

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 545why, one step back
545

Merge pull request #1149 from davidbrochart/fix_docDavid Lordbefore adoption2a70ef2

lines 546–557why, one step back
546- Template rendering requires an event loop to be available to the
547 current thread. :func:`asyncio.get_event_loop` must return an event548 loop.549- The compiled code uses ``await`` for functions and attributes, and550 uses ``async for`` loops. In order to support using both async and551 sync functions in this context, a small wrapper is placed around552 all calls and access, which add overhead compared to purely async553 code.554- Sync methods and filters become wrappers around their corresponding555 async implementations where needed. For example, ``render`` invokes556 ``async_render``, and ``|map`` supports async iterables.557

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 558why, one step back
558Awaitable objects can be returned from functions in templates and any

Merge pull request #1149 from davidbrochart/fix_docDavid Lordbefore adoption2a70ef2

lines 559–563why, one step back
559function call in a template will automatically await the result. The
560``await`` you would normally add in Python is implied. For example, you561can provide a method that asynchronously loads data from a database, and562from the template designer's point of view it can be called like any563other function.

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 564–573why, one step back
564
565566.. _policies:567568Policies569--------570571Starting with Jinja 2.9 policies can be configured on the environment572which can slightly influence how filters and other template constructs573behave. They can be configured with the

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 574why, one step back
574:attr:`~jinja2.Environment.policies` attribute.

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 575–580why, one step back
575
576Example::577578 env.policies['urlize.rel'] = 'nofollow noopener'579580``compiler.ascii_str``:

Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205

line 581why, one step back
581 This boolean controls on Python 2 if Jinja should store ASCII only

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 582–589why, one step back
582 literals as bytestring instead of unicode strings. This used to be
583 always enabled for Jinja versions below 2.9 and now can be changed.584 Traditionally it was done this way since some APIs in Python 2 failed585 badly for unicode strings (for instance the datetime strftime API).586 Now however sometimes the inverse is true (for instance str.format).587 If this is set to False then all strings are stored as unicode588 internally.589

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption5a8e771

lines 590–595why, one step back
590``truncate.leeway``:
591 Configures the leeway default for the `truncate` filter. Leeway as592 introduced in 2.9 but to restore compatibility with older templates593 it can be configured to `0` to get the old behavior back. The default594 is `5`.595

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 596–616why, one step back
596``urlize.rel``:
597 A string that defines the items for the `rel` attribute of generated598 links with the `urlize` filter. These items are always added. The599 default is `noopener`.600601``urlize.target``:602 The default target that is issued for links from the `urlize` filter603 if no other target is defined by the call explicitly.604605``json.dumps_function``:606 If this is set to a value other than `None` then the `tojson` filter607 will dump with this function instead of the default one. Note that608 this function should accept arbitrary extra arguments which might be609 passed in the future from the filter. Currently the only argument610 that might be passed is `indent`. The default dump function is611 ``json.dumps``.612613``json.dumps_kwargs``:614 Keyword arguments to be passed to the dump function. The default is615 ``{'sort_keys': True}``.616

Add support for `{% trans trimmed ... %}`Adrian Moennichbefore adoptione605ff1

lines 617–623why, one step back
617.. _ext-i18n-trimmed:
618619``ext.i18n.trimmed``:620 If this is set to `True`, ``{% trans %}`` blocks of the621 :ref:`i18n-extension` will always unify linebreaks and surrounding622 whitespace as if the `trimmed` modifier was used.623

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 624–628why, one step back
624
625Utilities626---------627628These helper functions and classes are useful if you add custom filters or

Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205

line 629why, one step back
629functions to a Jinja environment.

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 630why, one step back
630

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 631why, one step back
631.. autofunction:: jinja2.environmentfilter

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 632why, one step back
632

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 633why, one step back
633.. autofunction:: jinja2.contextfilter

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 634why, one step back
634

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 635why, one step back
635.. autofunction:: jinja2.evalcontextfilter

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 636why, one step back
636

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 637why, one step back
637.. autofunction:: jinja2.environmentfunction

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 638why, one step back
638

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 639why, one step back
639.. autofunction:: jinja2.contextfunction

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 640why, one step back
640

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 641why, one step back
641.. autofunction:: jinja2.evalcontextfunction

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 642–651why, one step back
642
643.. function:: escape(s)644645 Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s`646 to HTML-safe sequences. Use this if you need to display text that might647 contain such characters in HTML. This function will not escaped objects648 that do have an HTML representation such as already escaped data.649650 The return value is a :class:`Markup` string.651

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 652why, one step back
652.. autofunction:: jinja2.clear_caches

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 653why, one step back
653

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 654why, one step back
654.. autofunction:: jinja2.is_undefined

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 655why, one step back
655

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 656why, one step back
656.. autoclass:: jinja2.Markup([string])

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 657–660why, one step back
657 :members: escape, unescape, striptags
658659.. admonition:: Note660

Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205

line 661why, one step back
661 The Jinja :class:`Markup` class is compatible with at least Pylons and

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 662–668why, one step back
662 Genshi. It's expected that more template engines and framework will pick
663 up the `__html__` concept soon.664665666Exceptions667----------668

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 669why, one step back
669.. autoexception:: jinja2.TemplateError

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 670why, one step back
670

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 671why, one step back
671.. autoexception:: jinja2.UndefinedError

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 672why, one step back
672

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 673why, one step back
673.. autoexception:: jinja2.TemplateNotFound

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 674why, one step back
674

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 675why, one step back
675.. autoexception:: jinja2.TemplatesNotFound

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 676why, one step back
676

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 677why, one step back
677.. autoexception:: jinja2.TemplateSyntaxError

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 678–699why, one step back
678
679 .. attribute:: message680681 The error message as utf-8 bytestring.682683 .. attribute:: lineno684685 The line number where the error occurred686687 .. attribute:: name688689 The load name for the template as unicode string.690691 .. attribute:: filename692693 The filename that loaded the template as bytestring in the encoding694 of the file system (most likely utf-8 or mbcs on Windows systems).695696 The reason why the filename and error message are bytestrings and not697 unicode strings is that Python 2.x is not using unicode for exceptions698 and tracebacks as well as the compiler. This will change with Python 3.699

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 700why, one step back
700.. autoexception:: jinja2.TemplateRuntimeError

Merge pull request #684 from ThiefMaster/set-namespacesAdrianbefore adoptionc7dfa21

line 701why, one step back
701

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 702why, one step back
702.. autoexception:: jinja2.TemplateAssertionError

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 703–743why, one step back
703
704705.. _writing-filters:706707Custom Filters708--------------709710Custom filters are just regular Python functions that take the left side of711the filter as first argument and the arguments passed to the filter as712extra arguments or keyword arguments.713714For example in the filter ``{{ 42|myfilter(23) }}`` the function would be715called with ``myfilter(42, 23)``. Here for example a simple filter that can716be applied to datetime objects to format them::717718 def datetimeformat(value, format='%H:%M / %d-%m-%Y'):719 return value.strftime(format)720721You can register it on the template environment by updating the722:attr:`~Environment.filters` dict on the environment::723724 environment.filters['datetimeformat'] = datetimeformat725726Inside the template it can then be used as follows:727728.. sourcecode:: jinja729730 written on: {{ article.pub_date|datetimeformat }}731 publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}732733Filters can also be passed the current template context or environment. This734is useful if a filter wants to return an undefined value or check the current735:attr:`~Environment.autoescape` setting. For this purpose three decorators736exist: :func:`environmentfilter`, :func:`contextfilter` and737:func:`evalcontextfilter`.738739Here a small example filter that breaks a text into HTML line breaks and740paragraphs and marks the return value as safe HTML string if autoescaping is741enabled::742743 import re

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 744why, one step back
744 from jinja2 import evalcontextfilter, Markup, escape

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 745why, one step back
745

Merge pull request #929 from ExplodingCabbage/fix-nl2brDavid Lordbefore adoptiondd6c765

line 746why, one step back
746 _paragraph_re = re.compile(r'(?:\r\n|\r(?!\n)|\n){2,}')

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 747–756why, one step back
747
748 @evalcontextfilter749 def nl2br(eval_ctx, value):750 result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', Markup('<br>\n'))751 for p in _paragraph_re.split(escape(value)))752 if eval_ctx.autoescape:753 result = Markup(result)754 return result755756Context filters work the same just that the first argument is the current

Merge branch '2.9-maintenance'Armin Ronacherbefore adoptionc1cd154

line 757why, one step back
757active :class:`Context` rather than the environment.

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 758–809why, one step back
758
759760.. _eval-context:761762Evaluation Context763------------------764765The evaluation context (short eval context or eval ctx) is a new object766introduced in Jinja 2.4 that makes it possible to activate and deactivate767compiled features at runtime.768769Currently it is only used to enable and disable the automatic escaping but770can be used for extensions as well.771772In previous Jinja versions filters and functions were marked as773environment callables in order to check for the autoescape status from the774environment. In new versions it's encouraged to check the setting from the775evaluation context instead.776777Previous versions::778779 @environmentfilter780 def filter(env, value):781 result = do_something(value)782 if env.autoescape:783 result = Markup(result)784 return result785786In new versions you can either use a :func:`contextfilter` and access the787evaluation context from the actual context, or use a788:func:`evalcontextfilter` which directly passes the evaluation context to789the function::790791 @contextfilter792 def filter(context, value):793 result = do_something(value)794 if context.eval_ctx.autoescape:795 result = Markup(result)796 return result797798 @evalcontextfilter799 def filter(eval_ctx, value):800 result = do_something(value)801 if eval_ctx.autoescape:802 result = Markup(result)803 return result804805The evaluation context must not be modified at runtime. Modifications806must only happen with a :class:`nodes.EvalContextModifier` and807:class:`nodes.ScopedEvalContextModifier` from an extension, not on the808eval context object itself.809

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 810why, one step back
810.. autoclass:: jinja2.nodes.EvalContext

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 811–839why, one step back
811
812 .. attribute:: autoescape813814 `True` or `False` depending on if autoescaping is active or not.815816 .. attribute:: volatile817818 `True` if the compiler cannot evaluate some expressions at compile819 time. At runtime this should always be `False`.820821822.. _writing-tests:823824Custom Tests825------------826827Tests work like filters just that there is no way for a test to get access828to the environment or context and that they can't be chained. The return829value of a test should be `True` or `False`. The purpose of a test is to830give the template designers the possibility to perform type and conformability831checks.832833Here a simple test that checks if a variable is a prime number::834835 import math836837 def is_prime(n):838 if n == 2:839 return True

Merge branch '2.10.x'David Lordbefore adoption13cc9f4

line 840why, one step back
840 for i in range(2, int(math.ceil(math.sqrt(n))) + 1):

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 841–843why, one step back
841 if n % i == 0:
842 return False843 return True

Merge pull request #891 from jdufresne/wsDavid Lordbefore adoptionf9bb207

line 844why, one step back
844

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 845–917why, one step back
845
846You can register it on the template environment by updating the847:attr:`~Environment.tests` dict on the environment::848849 environment.tests['prime'] = is_prime850851A template designer can then use the test like this:852853.. sourcecode:: jinja854855 {% if 42 is prime %}856 42 is a prime number857 {% else %}858 42 is not a prime number859 {% endif %}860861862.. _global-namespace:863864The Global Namespace865--------------------866867Variables stored in the :attr:`Environment.globals` dict are special as they868are available for imported templates too, even if they are imported without869context. This is the place where you can put variables and functions870that should be available all the time. Additionally :attr:`Template.globals`871exist that are variables available to a specific template that are available872to all :meth:`~Template.render` calls.873874875.. _low-level-api:876877Low Level API878-------------879880The low level API exposes functionality that can be useful to understand some881implementation details, debugging purposes or advanced :ref:`extension882<jinja-extensions>` techniques. Unless you know exactly what you are doing we883don't recommend using any of those.884885.. automethod:: Environment.lex886887.. automethod:: Environment.parse888889.. automethod:: Environment.preprocess890891.. automethod:: Template.new_context892893.. method:: Template.root_render_func(context)894895 This is the low level render function. It's passed a :class:`Context`896 that has to be created by :meth:`new_context` of the same template or897 a compatible template. This render function is generated by the898 compiler from the template code and returns a generator that yields899 unicode strings.900901 If an exception in the template code happens the template engine will902 not rewrite the exception but pass through the original one. As a903 matter of fact this function should only be called from within a904 :meth:`render` / :meth:`generate` / :meth:`stream` call.905906.. attribute:: Template.blocks907908 A dict of block render functions. Each of these functions works exactly909 like the :meth:`root_render_func` with the same limitations.910911.. attribute:: Template.is_up_to_date912913 This attribute is `False` if there is a newer version of the template914 available, otherwise `True`.915916.. admonition:: Note917

Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205

lines 918–920why, one step back
918 The low-level API is fragile. Future Jinja versions will try not to
919 change it in a backwards incompatible way but modifications in the Jinja920 core may shine through. For example if Jinja introduces a new AST node

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

lines 921–932why, one step back
921 in later versions that may be returned by :meth:`~Environment.parse`.
922923The Meta API924------------925926.. versionadded:: 2.2927928The meta API returns some information about abstract syntax trees that929could help applications to implement more advanced template concepts. All930the functions of the meta API operate on an abstract syntax tree as931returned by the :meth:`Environment.parse` method.932

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 933why, one step back
933.. autofunction:: jinja2.meta.find_undeclared_variables

Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4

line 934why, one step back
934

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

line 935why, one step back
935.. autofunction:: jinja2.meta.find_referenced_templates