blob: 99270ec9fd9a5aa4074a21911322082d28e203e0 [file] [log] [blame]
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +02001API
2===
3
4.. module:: jinja2
jaba811d862019-06-06 03:04:36 +00005 :noindex:
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +02006 :synopsis: public Jinja2 API
7
8This document describes the API to Jinja2 and not the template language. It
9will be most useful as reference to those implementing the template interface
10to the application and not those who are creating Jinja2 templates.
11
12Basics
13------
14
15Jinja2 uses a central object called the template :class:`Environment`.
Carl A Dunhamd5463582014-01-18 15:26:10 -060016Instances of this class are used to store the configuration and global objects,
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020017and are used to load templates from the file system or other locations.
Armin Ronacher0aa0f582009-03-18 01:01:36 +010018Even if you are creating templates from strings by using the constructor of
Armin Ronacher61a5a242008-05-26 12:07:44 +020019:class:`Template` class, an environment is created automatically for you,
20albeit a shared one.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020021
22Most applications will create one :class:`Environment` object on application
Jon Dufresne148b6fb2018-08-29 20:58:03 -070023initialization and use that to load templates. In some cases however, it's
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020024useful to have multiple environments side by side, if different configurations
25are in use.
26
27The simplest way to configure Jinja2 to load templates for your application
28looks roughly like this::
29
Armin Ronacherb81a8a32017-01-07 16:13:39 +010030 from jinja2 import Environment, PackageLoader, select_autoescape
31 env = Environment(
32 loader=PackageLoader('yourapplication', 'templates'),
33 autoescape=select_autoescape(['html', 'xml'])
34 )
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020035
36This will create a template environment with the default settings and a
37loader that looks up the templates in the `templates` folder inside the
38`yourapplication` python package. Different loaders are available
39and you can also write your own if you want to load templates from a
Armin Ronacherb81a8a32017-01-07 16:13:39 +010040database or other resources. This also enables autoescaping for HTML and
41XML files.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020042
43To load a template from this environment you just have to call the
44:meth:`get_template` method which then returns the loaded :class:`Template`::
45
46 template = env.get_template('mytemplate.html')
47
48To render it with some variables, just call the :meth:`render` method::
49
Deepak Amin4965fac2019-05-31 14:17:35 -040050 print(template.render(the='variables', go='here'))
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020051
Éric Araujof6b654d2015-05-29 16:57:10 -040052Using a template loader rather than passing strings to :class:`Template`
Armin Ronacher61a5a242008-05-26 12:07:44 +020053or :meth:`Environment.from_string` has multiple advantages. Besides being
54a lot easier to use it also enables template inheritance.
55
Armin Ronacherb81a8a32017-01-07 16:13:39 +010056.. admonition:: Notes on Autoescaping
57
58 In future versions of Jinja2 we might enable autoescaping by default
59 for security reasons. As such you are encouraged to explicitly
60 configure autoescaping now instead of relying on the default.
61
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020062
Armin Ronacherf3c35c42008-05-23 23:18:14 +020063Unicode
64-------
65
Armin Ronacher656d5e72010-02-09 01:31:47 +010066Jinja2 is using Unicode internally which means that you have to pass Unicode
Armin Ronacherf3c35c42008-05-23 23:18:14 +020067objects to the render function or bytestrings that only consist of ASCII
68characters. Additionally newlines are normalized to one end of line
69sequence which is per default UNIX style (``\n``).
70
Armin Ronacher61a5a242008-05-26 12:07:44 +020071Python 2.x supports two ways of representing string objects. One is the
72`str` type and the other is the `unicode` type, both of which extend a type
73called `basestring`. Unfortunately the default is `str` which should not
74be used to store text based information unless only ASCII characters are
Armin Ronacher0aa0f582009-03-18 01:01:36 +010075used. With Python 2.6 it is possible to make `unicode` the default on a per
Armin Ronacher61a5a242008-05-26 12:07:44 +020076module level and with Python 3 it will be the default.
77
Armin Ronacher656d5e72010-02-09 01:31:47 +010078To explicitly use a Unicode string you have to prefix the string literal
Armin Ronacher61a5a242008-05-26 12:07:44 +020079with a `u`: ``u'Hänsel und Gretel sagen Hallo'``. That way Python will
Armin Ronacher656d5e72010-02-09 01:31:47 +010080store the string as Unicode by decoding the string with the character
Armin Ronacher61a5a242008-05-26 12:07:44 +020081encoding from the current Python module. If no encoding is specified this
82defaults to 'ASCII' which means that you can't use any non ASCII identifier.
83
84To set a better module encoding add the following comment to the first or
Armin Ronacher656d5e72010-02-09 01:31:47 +010085second line of the Python module using the Unicode literal::
Armin Ronacher61a5a242008-05-26 12:07:44 +020086
87 # -*- coding: utf-8 -*-
88
89We recommend utf-8 as Encoding for Python modules and templates as it's
90possible to represent every Unicode character in utf-8 and because it's
91backwards compatible to ASCII. For Jinja2 the default encoding of templates
92is assumed to be utf-8.
93
Armin Ronacher656d5e72010-02-09 01:31:47 +010094It is not possible to use Jinja2 to process non-Unicode data. The reason
Armin Ronacher61a5a242008-05-26 12:07:44 +020095for this is that Jinja2 uses Unicode already on the language level. For
96example Jinja2 treats the non-breaking space as valid whitespace inside
97expressions which requires knowledge of the encoding or operating on an
Armin Ronacher656d5e72010-02-09 01:31:47 +010098Unicode string.
Armin Ronacher61a5a242008-05-26 12:07:44 +020099
Armin Ronacher656d5e72010-02-09 01:31:47 +0100100For more details about Unicode in Python have a look at the excellent
Armin Ronacher61a5a242008-05-26 12:07:44 +0200101`Unicode documentation`_.
102
Armin Ronacher58f351d2008-05-28 21:30:14 +0200103Another important thing is how Jinja2 is handling string literals in
Armin Ronacher656d5e72010-02-09 01:31:47 +0100104templates. A naive implementation would be using Unicode strings for
Armin Ronacher58f351d2008-05-28 21:30:14 +0200105all string literals but it turned out in the past that this is problematic
106as some libraries are typechecking against `str` explicitly. For example
Armin Ronacher656d5e72010-02-09 01:31:47 +0100107`datetime.strftime` does not accept Unicode arguments. To not break it
Armin Ronacher58f351d2008-05-28 21:30:14 +0200108completely Jinja2 is returning `str` for strings that fit into ASCII and
109for everything else `unicode`:
110
111>>> m = Template(u"{% set a, b = 'foo', 'föö' %}").module
112>>> m.a
113'foo'
114>>> m.b
115u'f\xf6\xf6'
116
Armin Ronacher61a5a242008-05-26 12:07:44 +0200117
David Lord06696562019-07-26 12:12:41 -0700118.. _Unicode documentation: https://docs.python.org/3/howto/unicode.html
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200119
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200120High Level API
121--------------
122
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200123The high-level API is the API you will use in the application to load and
124render Jinja2 templates. The :ref:`low-level-api` on the other side is only
125useful if you want to dig deeper into Jinja2 or :ref:`develop extensions
126<jinja-extensions>`.
127
Armin Ronacher5411ce72008-05-25 11:36:22 +0200128.. autoclass:: Environment([options])
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100129 :members: from_string, get_template, select_template,
Armin Ronacher46844982011-01-29 20:19:58 +0100130 get_or_select_template, join_path, extend, compile_expression,
Armin Ronacher94638502011-09-26 00:41:25 +0200131 compile_templates, list_templates, add_extension
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200132
133 .. attribute:: shared
134
135 If a template was created by using the :class:`Template` constructor
136 an environment is created automatically. These environments are
137 created as shared environments which means that multiple templates
138 may have the same anonymous environment. For all shared environments
139 this attribute is `True`, else `False`.
140
141 .. attribute:: sandboxed
142
143 If the environment is sandboxed this attribute is `True`. For the
144 sandbox mode have a look at the documentation for the
145 :class:`~jinja2.sandbox.SandboxedEnvironment`.
146
147 .. attribute:: filters
148
149 A dict of filters for this environment. As long as no template was
Armin Ronacher7259c762008-04-30 13:03:59 +0200150 loaded it's safe to add new filters or remove old. For custom filters
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200151 see :ref:`writing-filters`. For valid filter names have a look at
152 :ref:`identifier-naming`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200153
154 .. attribute:: tests
155
Lukas Meuserad48a2e2008-05-01 18:19:57 +0200156 A dict of test functions for this environment. As long as no
157 template was loaded it's safe to modify this dict. For custom tests
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200158 see :ref:`writing-tests`. For valid test names have a look at
159 :ref:`identifier-naming`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200160
161 .. attribute:: globals
162
163 A dict of global variables. These variables are always available
Armin Ronacher981cbf62008-05-13 09:12:27 +0200164 in a template. As long as no template was loaded it's safe
Armin Ronacher7259c762008-04-30 13:03:59 +0200165 to modify this dict. For more details see :ref:`global-namespace`.
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200166 For valid object names have a look at :ref:`identifier-naming`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200167
Armin Ronachere2535202016-12-31 00:43:50 +0100168 .. attribute:: policies
169
170 A dictionary with :ref:`policies`. These can be reconfigured to
171 change the runtime behavior or certain template features. Usually
172 these are security related.
173
ThiefMaster14936312015-04-06 13:54:14 +0200174 .. attribute:: code_generator_class
175
176 The class used for code generation. This should not be changed
177 in most cases, unless you need to modify the Python code a
178 template compiles to.
179
ThiefMasterf22fdd52015-04-06 14:08:46 +0200180 .. attribute:: context_class
181
182 The context used for templates. This should not be changed
183 in most cases, unless you need to modify internals of how
184 template variables are handled. For details, see
185 :class:`~jinja2.runtime.Context`.
186
Armin Ronachered98cac2008-05-07 08:42:11 +0200187 .. automethod:: overlay([options])
188
Armin Ronacher58f351d2008-05-28 21:30:14 +0200189 .. method:: undefined([hint, obj, name, exc])
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200190
Armin Ronacher5411ce72008-05-25 11:36:22 +0200191 Creates a new :class:`Undefined` object for `name`. This is useful
192 for filters or functions that may return undefined objects for
193 some operations. All parameters except of `hint` should be provided
194 as keyword parameters for better readability. The `hint` is used as
195 error message for the exception if provided, otherwise the error
Armin Ronacher0aa0f582009-03-18 01:01:36 +0100196 message will be generated from `obj` and `name` automatically. The exception
Armin Ronacher5411ce72008-05-25 11:36:22 +0200197 provided as `exc` is raised if something with the generated undefined
198 object is done that the undefined object does not allow. The default
199 exception is :exc:`UndefinedError`. If a `hint` is provided the
Alex Chan972c0302015-04-05 22:42:34 +0100200 `name` may be omitted.
Armin Ronacher5411ce72008-05-25 11:36:22 +0200201
202 The most common way to create an undefined object is by providing
203 a name only::
204
205 return environment.undefined(name='some_name')
206
207 This means that the name `some_name` is not defined. If the name
208 was from an attribute of an object it makes sense to tell the
209 undefined object the holder object to improve the error message::
210
211 if not hasattr(obj, 'attr'):
212 return environment.undefined(obj=obj, name='attr')
213
214 For a more complex example you can provide a hint. For example
215 the :func:`first` filter creates an undefined object that way::
216
Jon Dufresne148b6fb2018-08-29 20:58:03 -0700217 return environment.undefined('no first item, sequence was empty')
Armin Ronacher5411ce72008-05-25 11:36:22 +0200218
219 If it the `name` or `obj` is known (for example because an attribute
Alex Chan972c0302015-04-05 22:42:34 +0100220 was accessed) it should be passed to the undefined object, even if
Armin Ronacher5411ce72008-05-25 11:36:22 +0200221 a custom `hint` is provided. This gives undefined objects the
222 possibility to enhance the error message.
223
224.. autoclass:: Template
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200225 :members: module, make_module
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200226
Armin Ronacher7259c762008-04-30 13:03:59 +0200227 .. attribute:: globals
228
Armin Ronachered98cac2008-05-07 08:42:11 +0200229 The dict with the globals of that template. It's unsafe to modify
230 this dict as it may be shared with other templates or the environment
231 that loaded the template.
Armin Ronacher7259c762008-04-30 13:03:59 +0200232
233 .. attribute:: name
234
Armin Ronachered98cac2008-05-07 08:42:11 +0200235 The loading name of the template. If the template was loaded from a
236 string this is `None`.
237
Armin Ronacher5411ce72008-05-25 11:36:22 +0200238 .. attribute:: filename
239
240 The filename of the template on the file system if it was loaded from
241 there. Otherwise this is `None`.
242
Armin Ronachered98cac2008-05-07 08:42:11 +0200243 .. automethod:: render([context])
244
245 .. automethod:: generate([context])
246
247 .. automethod:: stream([context])
Armin Ronacher7259c762008-04-30 13:03:59 +0200248
Armin Ronacherd8326d92016-12-28 22:51:46 +0100249 .. automethod:: render_async([context])
250
251 .. automethod:: generate_async([context])
252
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200253
Armin Ronacher6df604e2008-05-23 22:18:38 +0200254.. autoclass:: jinja2.environment.TemplateStream()
Armin Ronacher74b51062008-06-17 11:28:59 +0200255 :members: disable_buffering, enable_buffering, dump
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200256
257
Armin Ronacher1da23d12010-04-05 18:11:18 +0200258Autoescaping
259------------
260
Armin Ronachera27a5032017-01-07 15:55:20 +0100261.. versionchanged:: 2.4
Armin Ronacher1da23d12010-04-05 18:11:18 +0200262
Armin Ronachera27a5032017-01-07 15:55:20 +0100263Jinja2 now comes with autoescaping support. As of Jinja 2.9 the
264autoescape extension is removed and built-in. However autoescaping is
Armin Ronacherb81a8a32017-01-07 16:13:39 +0100265not yet enabled by default though this will most likely change in the
266future. It's recommended to configure a sensible default for
267autoescaping. This makes it possible to enable and disable autoescaping
268on a per-template basis (HTML versus text for instance).
269
270.. autofunction:: jinja2.select_autoescape
Armin Ronacher1da23d12010-04-05 18:11:18 +0200271
272Here a recommended setup that enables autoescaping for templates ending
273in ``'.html'``, ``'.htm'`` and ``'.xml'`` and disabling it by default
Armin Ronacherb81a8a32017-01-07 16:13:39 +0100274for all other extensions. You can use the :func:`~jinja2.select_autoescape`
275function for this::
Armin Ronacher1da23d12010-04-05 18:11:18 +0200276
Armin Ronacherb81a8a32017-01-07 16:13:39 +0100277 from jinja2 import Environment, select_autoescape
278 env = Environment(autoescape=select_autoescape(['html', 'htm', 'xml']),
Armin Ronachera27a5032017-01-07 15:55:20 +0100279 loader=PackageLoader('mypackage'))
Armin Ronacher1da23d12010-04-05 18:11:18 +0200280
Armin Ronacherb81a8a32017-01-07 16:13:39 +0100281The :func:`~jinja.select_autoescape` function returns a function that
Unknown778ccb22017-11-08 20:02:28 -0500282works roughly like this::
Armin Ronacherb81a8a32017-01-07 16:13:39 +0100283
284 def autoescape(template_name):
285 if template_name is None:
286 return False
287 if template_name.endswith(('.html', '.htm', '.xml'))
288
Armin Ronacher1da23d12010-04-05 18:11:18 +0200289When implementing a guessing autoescape function, make sure you also
290accept `None` as valid template name. This will be passed when generating
Armin Ronacherb81a8a32017-01-07 16:13:39 +0100291templates from strings. You should always configure autoescaping as
292defaults in the future might change.
Armin Ronacher1da23d12010-04-05 18:11:18 +0200293
294Inside the templates the behaviour can be temporarily changed by using
295the `autoescape` block (see :ref:`autoescape-overrides`).
296
297
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200298.. _identifier-naming:
299
300Notes on Identifiers
Armin Ronacher5411ce72008-05-25 11:36:22 +0200301--------------------
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200302
303Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to
304match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters
305are currently not allowed. This limitation will probably go away as soon as
306unicode identifiers are fully specified for Python 3.
307
308Filters and tests are looked up in separate namespaces and have slightly
309modified identifier syntax. Filters and tests may contain dots to group
310filters and tests by topic. For example it's perfectly valid to add a
311function into the filter dict and call it `to.unicode`. The regular
312expression for filter and test identifiers is
313``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.
314
315
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200316Undefined Types
317---------------
318
319These classes can be used as undefined types. The :class:`Environment`
320constructor takes an `undefined` parameter that can be one of those classes
321or a custom subclass of :class:`Undefined`. Whenever the template engine is
322unable to look up a name or access an attribute one of those objects is
323created and returned. Some operations on undefined values are then allowed,
324others fail.
325
Étienne Pelletier19133d42019-05-08 10:47:33 -0400326The closest to regular Python behavior is the :class:`StrictUndefined` which
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200327disallows all operations beside testing if it's an undefined object.
328
Armin Ronachera816bf42008-09-17 21:28:01 +0200329.. autoclass:: jinja2.Undefined()
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200330
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200331 .. attribute:: _undefined_hint
332
333 Either `None` or an unicode string with the error message for
334 the undefined object.
335
336 .. attribute:: _undefined_obj
337
338 Either `None` or the owner object that caused the undefined object
339 to be created (for example because an attribute does not exist).
340
341 .. attribute:: _undefined_name
342
343 The name for the undefined variable / attribute or just `None`
344 if no such information exists.
345
346 .. attribute:: _undefined_exception
347
348 The exception that the undefined object wants to raise. This
349 is usually one of :exc:`UndefinedError` or :exc:`SecurityError`.
350
351 .. method:: _fail_with_undefined_error(\*args, \**kwargs)
352
353 When called with any arguments this method raises
354 :attr:`_undefined_exception` with an error message generated
355 from the undefined hints stored on the undefined object.
356
Étienne Pelletier19133d42019-05-08 10:47:33 -0400357.. autoclass:: jinja2.ChainableUndefined()
358
Armin Ronachera816bf42008-09-17 21:28:01 +0200359.. autoclass:: jinja2.DebugUndefined()
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200360
Armin Ronachera816bf42008-09-17 21:28:01 +0200361.. autoclass:: jinja2.StrictUndefined()
Armin Ronacher5411ce72008-05-25 11:36:22 +0200362
Armin Ronacher6e9dfbf2014-06-06 22:14:45 +0600363There is also a factory function that can decorate undefined objects to
364implement logging on failures:
365
366.. autofunction:: jinja2.make_logging_undefined
367
Armin Ronacher5411ce72008-05-25 11:36:22 +0200368Undefined objects are created by calling :attr:`undefined`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200369
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200370.. admonition:: Implementation
371
372 :class:`Undefined` objects are implemented by overriding the special
373 `__underscore__` methods. For example the default :class:`Undefined`
374 class implements `__unicode__` in a way that it returns an empty
375 string, however `__int__` and others still fail with an exception. To
376 allow conversion to int by returning ``0`` you can implement your own::
377
378 class NullUndefined(Undefined):
379 def __int__(self):
380 return 0
381 def __float__(self):
382 return 0.0
383
384 To disallow a method, just override it and raise
Armin Ronacher58f351d2008-05-28 21:30:14 +0200385 :attr:`~Undefined._undefined_exception`. Because this is a very common
Ruben Garciaa9d557f2019-02-08 11:18:06 +0100386 idiom in undefined objects there is the helper method
Armin Ronacher58f351d2008-05-28 21:30:14 +0200387 :meth:`~Undefined._fail_with_undefined_error` that does the error raising
388 automatically. Here a class that works like the regular :class:`Undefined`
389 but chokes on iteration::
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200390
391 class NonIterableUndefined(Undefined):
392 __iter__ = Undefined._fail_with_undefined_error
393
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200394
Armin Ronacher7259c762008-04-30 13:03:59 +0200395The Context
396-----------
397
Armin Ronacher6df604e2008-05-23 22:18:38 +0200398.. autoclass:: jinja2.runtime.Context()
Armin Ronacherf35e2812008-05-06 16:04:10 +0200399 :members: resolve, get_exported, get_all
Armin Ronacher7259c762008-04-30 13:03:59 +0200400
401 .. attribute:: parent
402
403 A dict of read only, global variables the template looks up. These
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200404 can either come from another :class:`Context`, from the
Armin Ronacher5411ce72008-05-25 11:36:22 +0200405 :attr:`Environment.globals` or :attr:`Template.globals` or points
406 to a dict created by combining the globals with the variables
407 passed to the render function. It must not be altered.
Armin Ronacher7259c762008-04-30 13:03:59 +0200408
409 .. attribute:: vars
410
411 The template local variables. This list contains environment and
412 context functions from the :attr:`parent` scope as well as local
413 modifications and exported variables from the template. The template
414 will modify this dict during template evaluation but filters and
415 context functions are not allowed to modify it.
416
417 .. attribute:: environment
418
419 The environment that loaded the template.
420
421 .. attribute:: exported_vars
422
423 This set contains all the names the template exports. The values for
424 the names are in the :attr:`vars` dict. In order to get a copy of the
425 exported variables as dict, :meth:`get_exported` can be used.
426
427 .. attribute:: name
428
429 The load name of the template owning this context.
430
431 .. attribute:: blocks
432
433 A dict with the current mapping of blocks in the template. The keys
434 in this dict are the names of the blocks, and the values a list of
435 blocks registered. The last item in each list is the current active
436 block (latest in the inheritance chain).
437
Armin Ronacherfe150f32010-03-15 02:42:41 +0100438 .. attribute:: eval_ctx
439
440 The current :ref:`eval-context`.
441
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200442 .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs)
443
444
445.. admonition:: Implementation
446
447 Context is immutable for the same reason Python's frame locals are
448 immutable inside functions. Both Jinja2 and Python are not using the
449 context / frame locals as data storage for variables but only as primary
450 data source.
451
452 When a template accesses a variable the template does not define, Jinja2
453 looks up the variable in the context, after that the variable is treated
454 as if it was defined in the template.
455
Armin Ronacher7259c762008-04-30 13:03:59 +0200456
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200457.. _loaders:
458
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200459Loaders
460-------
461
462Loaders are responsible for loading templates from a resource such as the
Armin Ronacher7259c762008-04-30 13:03:59 +0200463file system. The environment will keep the compiled modules in memory like
464Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in
465size by default and templates are automatically reloaded.
Armin Ronachercda43df2008-05-03 17:10:05 +0200466All loaders are subclasses of :class:`BaseLoader`. If you want to create your
Armin Ronachercda43df2008-05-03 17:10:05 +0200467own loader, subclass :class:`BaseLoader` and override `get_source`.
468
Armin Ronachera816bf42008-09-17 21:28:01 +0200469.. autoclass:: jinja2.BaseLoader
Armin Ronachercda43df2008-05-03 17:10:05 +0200470 :members: get_source, load
471
472Here a list of the builtin loaders Jinja2 provides:
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200473
Armin Ronachera816bf42008-09-17 21:28:01 +0200474.. autoclass:: jinja2.FileSystemLoader
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200475
Armin Ronachera816bf42008-09-17 21:28:01 +0200476.. autoclass:: jinja2.PackageLoader
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200477
Armin Ronachera816bf42008-09-17 21:28:01 +0200478.. autoclass:: jinja2.DictLoader
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200479
Armin Ronachera816bf42008-09-17 21:28:01 +0200480.. autoclass:: jinja2.FunctionLoader
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200481
Armin Ronachera816bf42008-09-17 21:28:01 +0200482.. autoclass:: jinja2.PrefixLoader
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200483
Armin Ronachera816bf42008-09-17 21:28:01 +0200484.. autoclass:: jinja2.ChoiceLoader
485
Armin Ronacher46844982011-01-29 20:19:58 +0100486.. autoclass:: jinja2.ModuleLoader
487
Armin Ronachera816bf42008-09-17 21:28:01 +0200488
489.. _bytecode-cache:
490
491Bytecode Cache
492--------------
493
494Jinja 2.1 and higher support external bytecode caching. Bytecode caches make
495it possible to store the generated bytecode on the file system or a different
496location to avoid parsing the templates on first use.
497
498This is especially useful if you have a web application that is initialized on
499the first request and Jinja compiles many templates at once which slows down
500the application.
501
Jakub Wilk3fc008b2013-05-25 23:37:34 +0200502To use a bytecode cache, instantiate it and pass it to the :class:`Environment`.
Armin Ronachera816bf42008-09-17 21:28:01 +0200503
504.. autoclass:: jinja2.BytecodeCache
505 :members: load_bytecode, dump_bytecode, clear
506
507.. autoclass:: jinja2.bccache.Bucket
508 :members: write_bytecode, load_bytecode, bytecode_from_string,
509 bytecode_to_string, reset
510
511 .. attribute:: environment
512
513 The :class:`Environment` that created the bucket.
514
515 .. attribute:: key
516
517 The unique cache key for this bucket
518
519 .. attribute:: code
520
521 The bytecode if it's loaded, otherwise `None`.
522
523
524Builtin bytecode caches:
525
526.. autoclass:: jinja2.FileSystemBytecodeCache
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200527
Armin Ronacheraa1d17d2008-09-18 18:09:06 +0200528.. autoclass:: jinja2.MemcachedBytecodeCache
529
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200530
Armin Ronacherd8326d92016-12-28 22:51:46 +0100531Async Support
532-------------
533
534Starting with version 2.9, Jinja2 also supports the Python `async` and
535`await` constructs. As far as template designers go this feature is
536entirely opaque to them however as a developer you should be aware of how
537it's implemented as it influences what type of APIs you can safely expose
538to the template environment.
539
540First you need to be aware that by default async support is disabled as
541enabling it will generate different template code behind the scenes which
542passes everything through the asyncio event loop. This is important to
543understand because it has some impact to what you are doing:
544
545* template rendering will require an event loop to be set for the
546 current thread (``asyncio.get_event_loop`` needs to return one)
547* all template generation code internally runs async generators which
548 means that you will pay a performance penalty even if the non sync
549 methods are used!
550* The sync methods are based on async methods if the async mode is
551 enabled which means that `render` for instance will internally invoke
552 `render_async` and run it as part of the current event loop until the
553 execution finished.
554
555Awaitable objects can be returned from functions in templates and any
556function call in a template will automatically await the result. This
nwalsh199565337f82018-04-17 14:55:13 -0700557means that you can provide a method that asynchronously loads data
Armin Ronacherd8326d92016-12-28 22:51:46 +0100558from a database if you so desire and from the template designer's point of
559view this is just another function they can call. This means that the
560``await`` you would normally issue in Python is implied. However this
561only applies to function calls. If an attribute for instance would be an
Frank Sachsenheimd0f88112018-05-11 21:25:22 +0200562awaitable object then this would not result in the expected behavior.
Armin Ronacherd8326d92016-12-28 22:51:46 +0100563
564Likewise iterations with a `for` loop support async iterators.
565
Armin Ronachere2535202016-12-31 00:43:50 +0100566.. _policies:
567
568Policies
569--------
570
571Starting with Jinja 2.9 policies can be configured on the environment
572which can slightly influence how filters and other template constructs
573behave. They can be configured with the
574:attr:`~jinja2.Environment.policies` attribute.
575
576Example::
577
578 env.policies['urlize.rel'] = 'nofollow noopener'
579
Armin Ronacher028f0582017-01-07 14:57:44 +0100580``compiler.ascii_str``:
581 This boolean controls on Python 2 if Jinja2 should store ASCII only
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 failed
585 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 unicode
588 internally.
589
Armin Ronacherfb47dfa2017-01-10 09:21:14 +0100590``truncate.leeway``:
591 Configures the leeway default for the `truncate` filter. Leeway as
592 introduced in 2.9 but to restore compatibility with older templates
593 it can be configured to `0` to get the old behavior back. The default
594 is `5`.
595
Armin Ronachere2535202016-12-31 00:43:50 +0100596``urlize.rel``:
597 A string that defines the items for the `rel` attribute of generated
598 links with the `urlize` filter. These items are always added. The
599 default is `noopener`.
600
601``urlize.target``:
602 The default target that is issued for links from the `urlize` filter
603 if no other target is defined by the call explicitly.
604
Armin Ronachere71a1302017-01-06 21:33:51 +0100605``json.dumps_function``:
606 If this is set to a value other than `None` then the `tojson` filter
607 will dump with this function instead of the default one. Note that
608 this function should accept arbitrary extra arguments which might be
609 passed in the future from the filter. Currently the only argument
610 that might be passed is `indent`. The default dump function is
611 ``json.dumps``.
612
613``json.dumps_kwargs``:
614 Keyword arguments to be passed to the dump function. The default is
615 ``{'sort_keys': True}``.
616
Adrian Moenniche605ff12017-02-17 23:49:39 +0100617.. _ext-i18n-trimmed:
618
619``ext.i18n.trimmed``:
620 If this is set to `True`, ``{% trans %}`` blocks of the
621 :ref:`i18n-extension` will always unify linebreaks and surrounding
622 whitespace as if the `trimmed` modifier was used.
623
Armin Ronacherd8326d92016-12-28 22:51:46 +0100624
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200625Utilities
626---------
627
628These helper functions and classes are useful if you add custom filters or
629functions to a Jinja2 environment.
630
Armin Ronachera816bf42008-09-17 21:28:01 +0200631.. autofunction:: jinja2.environmentfilter
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200632
Armin Ronachera816bf42008-09-17 21:28:01 +0200633.. autofunction:: jinja2.contextfilter
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200634
Armin Ronacherfe150f32010-03-15 02:42:41 +0100635.. autofunction:: jinja2.evalcontextfilter
636
Armin Ronachera816bf42008-09-17 21:28:01 +0200637.. autofunction:: jinja2.environmentfunction
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200638
Armin Ronachera816bf42008-09-17 21:28:01 +0200639.. autofunction:: jinja2.contextfunction
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200640
Armin Ronacherfe150f32010-03-15 02:42:41 +0100641.. autofunction:: jinja2.evalcontextfunction
642
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200643.. function:: escape(s)
644
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200645 Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s`
646 to HTML-safe sequences. Use this if you need to display text that might
647 contain such characters in HTML. This function will not escaped objects
648 that do have an HTML representation such as already escaped data.
649
650 The return value is a :class:`Markup` string.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200651
Armin Ronachera816bf42008-09-17 21:28:01 +0200652.. autofunction:: jinja2.clear_caches
Armin Ronacher187bde12008-05-01 18:19:16 +0200653
Armin Ronachera816bf42008-09-17 21:28:01 +0200654.. autofunction:: jinja2.is_undefined
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200655
Armin Ronachera816bf42008-09-17 21:28:01 +0200656.. autoclass:: jinja2.Markup([string])
Armin Ronacher58f351d2008-05-28 21:30:14 +0200657 :members: escape, unescape, striptags
658
659.. admonition:: Note
660
661 The Jinja2 :class:`Markup` class is compatible with at least Pylons and
662 Genshi. It's expected that more template engines and framework will pick
663 up the `__html__` concept soon.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200664
665
666Exceptions
667----------
668
Armin Ronachera816bf42008-09-17 21:28:01 +0200669.. autoexception:: jinja2.TemplateError
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200670
Armin Ronachera816bf42008-09-17 21:28:01 +0200671.. autoexception:: jinja2.UndefinedError
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200672
Armin Ronachera816bf42008-09-17 21:28:01 +0200673.. autoexception:: jinja2.TemplateNotFound
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200674
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100675.. autoexception:: jinja2.TemplatesNotFound
676
Armin Ronachera816bf42008-09-17 21:28:01 +0200677.. autoexception:: jinja2.TemplateSyntaxError
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200678
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200679 .. attribute:: message
680
681 The error message as utf-8 bytestring.
682
683 .. attribute:: lineno
684
685 The line number where the error occurred
686
687 .. attribute:: name
688
689 The load name for the template as unicode string.
690
691 .. attribute:: filename
692
693 The filename that loaded the template as bytestring in the encoding
694 of the file system (most likely utf-8 or mbcs on Windows systems).
695
696 The reason why the filename and error message are bytestrings and not
697 unicode strings is that Python 2.x is not using unicode for exceptions
698 and tracebacks as well as the compiler. This will change with Python 3.
699
Adrian Moennichcc1d2872017-02-26 18:00:06 +0100700.. autoexception:: jinja2.TemplateRuntimeError
701
Armin Ronachera816bf42008-09-17 21:28:01 +0200702.. autoexception:: jinja2.TemplateAssertionError
Armin Ronacher7259c762008-04-30 13:03:59 +0200703
704
705.. _writing-filters:
706
707Custom Filters
708--------------
709
710Custom filters are just regular Python functions that take the left side of
Guillaume Paumier345e0ba2016-04-10 08:58:06 -0700711the filter as first argument and the arguments passed to the filter as
Armin Ronacher7259c762008-04-30 13:03:59 +0200712extra arguments or keyword arguments.
713
714For example in the filter ``{{ 42|myfilter(23) }}`` the function would be
715called with ``myfilter(42, 23)``. Here for example a simple filter that can
716be applied to datetime objects to format them::
717
718 def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
719 return value.strftime(format)
720
721You can register it on the template environment by updating the
722:attr:`~Environment.filters` dict on the environment::
723
724 environment.filters['datetimeformat'] = datetimeformat
725
726Inside the template it can then be used as follows:
727
728.. sourcecode:: jinja
729
730 written on: {{ article.pub_date|datetimeformat }}
731 publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}
732
733Filters can also be passed the current template context or environment. This
Armin Ronacher0aa0f582009-03-18 01:01:36 +0100734is useful if a filter wants to return an undefined value or check the current
Armin Ronacher2e3c9c72010-04-10 13:03:46 +0200735:attr:`~Environment.autoescape` setting. For this purpose three decorators
Armin Ronacherfe150f32010-03-15 02:42:41 +0100736exist: :func:`environmentfilter`, :func:`contextfilter` and
737:func:`evalcontextfilter`.
Armin Ronacher7259c762008-04-30 13:03:59 +0200738
739Here a small example filter that breaks a text into HTML line breaks and
740paragraphs and marks the return value as safe HTML string if autoescaping is
741enabled::
742
743 import re
Jeffrey Finkelstein449ef022011-07-01 15:46:54 -0700744 from jinja2 import evalcontextfilter, Markup, escape
Armin Ronacher7259c762008-04-30 13:03:59 +0200745
Mark Amery9e410c72018-11-25 17:49:22 +0000746 _paragraph_re = re.compile(r'(?:\r\n|\r(?!\n)|\n){2,}')
Armin Ronacher7259c762008-04-30 13:03:59 +0200747
Armin Ronacherfe150f32010-03-15 02:42:41 +0100748 @evalcontextfilter
749 def nl2br(eval_ctx, value):
Jörn Hees17024512014-06-15 18:31:16 +0200750 result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', Markup('<br>\n'))
Armin Ronacher7259c762008-04-30 13:03:59 +0200751 for p in _paragraph_re.split(escape(value)))
Armin Ronacherfe150f32010-03-15 02:42:41 +0100752 if eval_ctx.autoescape:
Armin Ronacher7259c762008-04-30 13:03:59 +0200753 result = Markup(result)
754 return result
755
756Context filters work the same just that the first argument is the current
Daniel van Flymen96f52e62017-03-01 14:10:34 -0500757active :class:`Context` rather than the environment.
Armin Ronacher7259c762008-04-30 13:03:59 +0200758
759
Armin Ronacherfe150f32010-03-15 02:42:41 +0100760.. _eval-context:
761
762Evaluation Context
763------------------
764
765The evaluation context (short eval context or eval ctx) is a new object
Jakub Wilk3fc008b2013-05-25 23:37:34 +0200766introduced in Jinja 2.4 that makes it possible to activate and deactivate
Armin Ronacherfe150f32010-03-15 02:42:41 +0100767compiled features at runtime.
768
769Currently it is only used to enable and disable the automatic escaping but
770can be used for extensions as well.
771
772In previous Jinja versions filters and functions were marked as
773environment callables in order to check for the autoescape status from the
774environment. In new versions it's encouraged to check the setting from the
775evaluation context instead.
776
777Previous versions::
778
779 @environmentfilter
780 def filter(env, value):
781 result = do_something(value)
782 if env.autoescape:
783 result = Markup(result)
784 return result
785
786In new versions you can either use a :func:`contextfilter` and access the
787evaluation context from the actual context, or use a
788:func:`evalcontextfilter` which directly passes the evaluation context to
789the function::
790
791 @contextfilter
792 def filter(context, value):
793 result = do_something(value)
794 if context.eval_ctx.autoescape:
795 result = Markup(result)
796 return result
797
798 @evalcontextfilter
799 def filter(eval_ctx, value):
800 result = do_something(value)
801 if eval_ctx.autoescape:
802 result = Markup(result)
803 return result
804
805The evaluation context must not be modified at runtime. Modifications
806must only happen with a :class:`nodes.EvalContextModifier` and
807:class:`nodes.ScopedEvalContextModifier` from an extension, not on the
808eval context object itself.
809
Armin Ronacher76ae15e2010-03-15 09:36:47 +0100810.. autoclass:: jinja2.nodes.EvalContext
Armin Ronacher30fda272010-03-15 03:06:04 +0100811
812 .. attribute:: autoescape
813
814 `True` or `False` depending on if autoescaping is active or not.
815
816 .. attribute:: volatile
817
818 `True` if the compiler cannot evaluate some expressions at compile
819 time. At runtime this should always be `False`.
820
821
Armin Ronacher7259c762008-04-30 13:03:59 +0200822.. _writing-tests:
823
824Custom Tests
825------------
826
Armin Ronachera5d8f552008-09-11 20:46:34 +0200827Tests work like filters just that there is no way for a test to get access
Armin Ronacher7259c762008-04-30 13:03:59 +0200828to the environment or context and that they can't be chained. The return
Armin Ronachera5d8f552008-09-11 20:46:34 +0200829value of a test should be `True` or `False`. The purpose of a test is to
Armin Ronacher7259c762008-04-30 13:03:59 +0200830give the template designers the possibility to perform type and conformability
831checks.
832
Armin Ronachera5d8f552008-09-11 20:46:34 +0200833Here a simple test that checks if a variable is a prime number::
Armin Ronacher7259c762008-04-30 13:03:59 +0200834
835 import math
836
837 def is_prime(n):
838 if n == 2:
839 return True
Deepak Amin4965fac2019-05-31 14:17:35 -0400840 for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
Armin Ronacher7259c762008-04-30 13:03:59 +0200841 if n % i == 0:
842 return False
843 return True
Jon Dufresne148b6fb2018-08-29 20:58:03 -0700844
Armin Ronacher7259c762008-04-30 13:03:59 +0200845
846You can register it on the template environment by updating the
847:attr:`~Environment.tests` dict on the environment::
848
849 environment.tests['prime'] = is_prime
850
851A template designer can then use the test like this:
852
853.. sourcecode:: jinja
854
855 {% if 42 is prime %}
856 42 is a prime number
857 {% else %}
858 42 is not a prime number
859 {% endif %}
860
861
862.. _global-namespace:
863
864The Global Namespace
865--------------------
866
Armin Ronacher981cbf62008-05-13 09:12:27 +0200867Variables stored in the :attr:`Environment.globals` dict are special as they
868are available for imported templates too, even if they are imported without
869context. This is the place where you can put variables and functions
870that should be available all the time. Additionally :attr:`Template.globals`
871exist that are variables available to a specific template that are available
872to all :meth:`~Template.render` calls.
Armin Ronacher5411ce72008-05-25 11:36:22 +0200873
874
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200875.. _low-level-api:
876
Armin Ronacher5411ce72008-05-25 11:36:22 +0200877Low Level API
878-------------
879
880The low level API exposes functionality that can be useful to understand some
881implementation details, debugging purposes or advanced :ref:`extension
Armin Ronacher61a5a242008-05-26 12:07:44 +0200882<jinja-extensions>` techniques. Unless you know exactly what you are doing we
883don't recommend using any of those.
Armin Ronacher5411ce72008-05-25 11:36:22 +0200884
885.. automethod:: Environment.lex
886
887.. automethod:: Environment.parse
888
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200889.. automethod:: Environment.preprocess
890
Armin Ronacher5411ce72008-05-25 11:36:22 +0200891.. automethod:: Template.new_context
892
893.. method:: Template.root_render_func(context)
894
895 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 or
897 a compatible template. This render function is generated by the
898 compiler from the template code and returns a generator that yields
899 unicode strings.
900
901 If an exception in the template code happens the template engine will
902 not rewrite the exception but pass through the original one. As a
903 matter of fact this function should only be called from within a
904 :meth:`render` / :meth:`generate` / :meth:`stream` call.
905
906.. attribute:: Template.blocks
907
908 A dict of block render functions. Each of these functions works exactly
909 like the :meth:`root_render_func` with the same limitations.
910
911.. attribute:: Template.is_up_to_date
912
913 This attribute is `False` if there is a newer version of the template
914 available, otherwise `True`.
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200915
916.. admonition:: Note
917
Armin Ronacher58f351d2008-05-28 21:30:14 +0200918 The low-level API is fragile. Future Jinja2 versions will try not to
919 change it in a backwards incompatible way but modifications in the Jinja2
920 core may shine through. For example if Jinja2 introduces a new AST node
921 in later versions that may be returned by :meth:`~Environment.parse`.
Armin Ronacher63cf9b82009-07-26 10:33:36 +0200922
923The Meta API
924------------
925
926.. versionadded:: 2.2
927
928The meta API returns some information about abstract syntax trees that
929could help applications to implement more advanced template concepts. All
930the functions of the meta API operate on an abstract syntax tree as
931returned by the :meth:`Environment.parse` method.
932
933.. autofunction:: jinja2.meta.find_undeclared_variables
934
935.. autofunction:: jinja2.meta.find_referenced_templates