blob: 8bf0fdfe0986e1fe73814c2aa6e9540bc3f65ec9 [file] [log] [blame]
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +02001API
2===
3
4.. module:: jinja2
5 :synopsis: public Jinja2 API
6
7This document describes the API to Jinja2 and not the template language. It
8will be most useful as reference to those implementing the template interface
9to the application and not those who are creating Jinja2 templates.
10
11Basics
12------
13
14Jinja2 uses a central object called the template :class:`Environment`.
Carl A Dunhamd5463582014-01-18 15:26:10 -060015Instances of this class are used to store the configuration and global objects,
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020016and are used to load templates from the file system or other locations.
Armin Ronacher0aa0f582009-03-18 01:01:36 +010017Even if you are creating templates from strings by using the constructor of
Armin Ronacher61a5a242008-05-26 12:07:44 +020018:class:`Template` class, an environment is created automatically for you,
19albeit a shared one.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020020
21Most applications will create one :class:`Environment` object on application
Kojo Idrissad48cb212016-04-10 14:04:46 -050022initialization and use that to load templates. In some cases however, it's
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020023useful to have multiple environments side by side, if different configurations
24are in use.
25
26The simplest way to configure Jinja2 to load templates for your application
27looks roughly like this::
28
29 from jinja2 import Environment, PackageLoader
30 env = Environment(loader=PackageLoader('yourapplication', 'templates'))
31
32This will create a template environment with the default settings and a
33loader that looks up the templates in the `templates` folder inside the
34`yourapplication` python package. Different loaders are available
35and you can also write your own if you want to load templates from a
36database or other resources.
37
38To load a template from this environment you just have to call the
39:meth:`get_template` method which then returns the loaded :class:`Template`::
40
41 template = env.get_template('mytemplate.html')
42
43To render it with some variables, just call the :meth:`render` method::
44
45 print template.render(the='variables', go='here')
46
Éric Araujof6b654d2015-05-29 16:57:10 -040047Using a template loader rather than passing strings to :class:`Template`
Armin Ronacher61a5a242008-05-26 12:07:44 +020048or :meth:`Environment.from_string` has multiple advantages. Besides being
49a lot easier to use it also enables template inheritance.
50
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020051
Armin Ronacherf3c35c42008-05-23 23:18:14 +020052Unicode
53-------
54
Armin Ronacher656d5e72010-02-09 01:31:47 +010055Jinja2 is using Unicode internally which means that you have to pass Unicode
Armin Ronacherf3c35c42008-05-23 23:18:14 +020056objects to the render function or bytestrings that only consist of ASCII
57characters. Additionally newlines are normalized to one end of line
58sequence which is per default UNIX style (``\n``).
59
Armin Ronacher61a5a242008-05-26 12:07:44 +020060Python 2.x supports two ways of representing string objects. One is the
61`str` type and the other is the `unicode` type, both of which extend a type
62called `basestring`. Unfortunately the default is `str` which should not
63be used to store text based information unless only ASCII characters are
Armin Ronacher0aa0f582009-03-18 01:01:36 +010064used. With Python 2.6 it is possible to make `unicode` the default on a per
Armin Ronacher61a5a242008-05-26 12:07:44 +020065module level and with Python 3 it will be the default.
66
Armin Ronacher656d5e72010-02-09 01:31:47 +010067To explicitly use a Unicode string you have to prefix the string literal
Armin Ronacher61a5a242008-05-26 12:07:44 +020068with a `u`: ``u'Hänsel und Gretel sagen Hallo'``. That way Python will
Armin Ronacher656d5e72010-02-09 01:31:47 +010069store the string as Unicode by decoding the string with the character
Armin Ronacher61a5a242008-05-26 12:07:44 +020070encoding from the current Python module. If no encoding is specified this
71defaults to 'ASCII' which means that you can't use any non ASCII identifier.
72
73To set a better module encoding add the following comment to the first or
Armin Ronacher656d5e72010-02-09 01:31:47 +010074second line of the Python module using the Unicode literal::
Armin Ronacher61a5a242008-05-26 12:07:44 +020075
76 # -*- coding: utf-8 -*-
77
78We recommend utf-8 as Encoding for Python modules and templates as it's
79possible to represent every Unicode character in utf-8 and because it's
80backwards compatible to ASCII. For Jinja2 the default encoding of templates
81is assumed to be utf-8.
82
Armin Ronacher656d5e72010-02-09 01:31:47 +010083It is not possible to use Jinja2 to process non-Unicode data. The reason
Armin Ronacher61a5a242008-05-26 12:07:44 +020084for this is that Jinja2 uses Unicode already on the language level. For
85example Jinja2 treats the non-breaking space as valid whitespace inside
86expressions which requires knowledge of the encoding or operating on an
Armin Ronacher656d5e72010-02-09 01:31:47 +010087Unicode string.
Armin Ronacher61a5a242008-05-26 12:07:44 +020088
Armin Ronacher656d5e72010-02-09 01:31:47 +010089For more details about Unicode in Python have a look at the excellent
Armin Ronacher61a5a242008-05-26 12:07:44 +020090`Unicode documentation`_.
91
Armin Ronacher58f351d2008-05-28 21:30:14 +020092Another important thing is how Jinja2 is handling string literals in
Armin Ronacher656d5e72010-02-09 01:31:47 +010093templates. A naive implementation would be using Unicode strings for
Armin Ronacher58f351d2008-05-28 21:30:14 +020094all string literals but it turned out in the past that this is problematic
95as some libraries are typechecking against `str` explicitly. For example
Armin Ronacher656d5e72010-02-09 01:31:47 +010096`datetime.strftime` does not accept Unicode arguments. To not break it
Armin Ronacher58f351d2008-05-28 21:30:14 +020097completely Jinja2 is returning `str` for strings that fit into ASCII and
98for everything else `unicode`:
99
100>>> m = Template(u"{% set a, b = 'foo', 'föö' %}").module
101>>> m.a
102'foo'
103>>> m.b
104u'f\xf6\xf6'
105
Armin Ronacher61a5a242008-05-26 12:07:44 +0200106
107.. _Unicode documentation: http://docs.python.org/dev/howto/unicode.html
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200108
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200109High Level API
110--------------
111
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200112The high-level API is the API you will use in the application to load and
113render Jinja2 templates. The :ref:`low-level-api` on the other side is only
114useful if you want to dig deeper into Jinja2 or :ref:`develop extensions
115<jinja-extensions>`.
116
Armin Ronacher5411ce72008-05-25 11:36:22 +0200117.. autoclass:: Environment([options])
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100118 :members: from_string, get_template, select_template,
Armin Ronacher46844982011-01-29 20:19:58 +0100119 get_or_select_template, join_path, extend, compile_expression,
Armin Ronacher94638502011-09-26 00:41:25 +0200120 compile_templates, list_templates, add_extension
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200121
122 .. attribute:: shared
123
124 If a template was created by using the :class:`Template` constructor
125 an environment is created automatically. These environments are
126 created as shared environments which means that multiple templates
127 may have the same anonymous environment. For all shared environments
128 this attribute is `True`, else `False`.
129
130 .. attribute:: sandboxed
131
132 If the environment is sandboxed this attribute is `True`. For the
133 sandbox mode have a look at the documentation for the
134 :class:`~jinja2.sandbox.SandboxedEnvironment`.
135
136 .. attribute:: filters
137
138 A dict of filters for this environment. As long as no template was
Armin Ronacher7259c762008-04-30 13:03:59 +0200139 loaded it's safe to add new filters or remove old. For custom filters
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200140 see :ref:`writing-filters`. For valid filter names have a look at
141 :ref:`identifier-naming`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200142
143 .. attribute:: tests
144
Lukas Meuserad48a2e2008-05-01 18:19:57 +0200145 A dict of test functions for this environment. As long as no
146 template was loaded it's safe to modify this dict. For custom tests
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200147 see :ref:`writing-tests`. For valid test names have a look at
148 :ref:`identifier-naming`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200149
150 .. attribute:: globals
151
152 A dict of global variables. These variables are always available
Armin Ronacher981cbf62008-05-13 09:12:27 +0200153 in a template. As long as no template was loaded it's safe
Armin Ronacher7259c762008-04-30 13:03:59 +0200154 to modify this dict. For more details see :ref:`global-namespace`.
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200155 For valid object names have a look at :ref:`identifier-naming`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200156
Armin Ronachere2535202016-12-31 00:43:50 +0100157 .. attribute:: policies
158
159 A dictionary with :ref:`policies`. These can be reconfigured to
160 change the runtime behavior or certain template features. Usually
161 these are security related.
162
ThiefMaster14936312015-04-06 13:54:14 +0200163 .. attribute:: code_generator_class
164
165 The class used for code generation. This should not be changed
166 in most cases, unless you need to modify the Python code a
167 template compiles to.
168
ThiefMasterf22fdd52015-04-06 14:08:46 +0200169 .. attribute:: context_class
170
171 The context used for templates. This should not be changed
172 in most cases, unless you need to modify internals of how
173 template variables are handled. For details, see
174 :class:`~jinja2.runtime.Context`.
175
Armin Ronachered98cac2008-05-07 08:42:11 +0200176 .. automethod:: overlay([options])
177
Armin Ronacher58f351d2008-05-28 21:30:14 +0200178 .. method:: undefined([hint, obj, name, exc])
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200179
Armin Ronacher5411ce72008-05-25 11:36:22 +0200180 Creates a new :class:`Undefined` object for `name`. This is useful
181 for filters or functions that may return undefined objects for
182 some operations. All parameters except of `hint` should be provided
183 as keyword parameters for better readability. The `hint` is used as
184 error message for the exception if provided, otherwise the error
Armin Ronacher0aa0f582009-03-18 01:01:36 +0100185 message will be generated from `obj` and `name` automatically. The exception
Armin Ronacher5411ce72008-05-25 11:36:22 +0200186 provided as `exc` is raised if something with the generated undefined
187 object is done that the undefined object does not allow. The default
188 exception is :exc:`UndefinedError`. If a `hint` is provided the
Alex Chan972c0302015-04-05 22:42:34 +0100189 `name` may be omitted.
Armin Ronacher5411ce72008-05-25 11:36:22 +0200190
191 The most common way to create an undefined object is by providing
192 a name only::
193
194 return environment.undefined(name='some_name')
195
196 This means that the name `some_name` is not defined. If the name
197 was from an attribute of an object it makes sense to tell the
198 undefined object the holder object to improve the error message::
199
200 if not hasattr(obj, 'attr'):
201 return environment.undefined(obj=obj, name='attr')
202
203 For a more complex example you can provide a hint. For example
204 the :func:`first` filter creates an undefined object that way::
205
206 return environment.undefined('no first item, sequence was empty')
207
208 If it the `name` or `obj` is known (for example because an attribute
Alex Chan972c0302015-04-05 22:42:34 +0100209 was accessed) it should be passed to the undefined object, even if
Armin Ronacher5411ce72008-05-25 11:36:22 +0200210 a custom `hint` is provided. This gives undefined objects the
211 possibility to enhance the error message.
212
213.. autoclass:: Template
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200214 :members: module, make_module
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200215
Armin Ronacher7259c762008-04-30 13:03:59 +0200216 .. attribute:: globals
217
Armin Ronachered98cac2008-05-07 08:42:11 +0200218 The dict with the globals of that template. It's unsafe to modify
219 this dict as it may be shared with other templates or the environment
220 that loaded the template.
Armin Ronacher7259c762008-04-30 13:03:59 +0200221
222 .. attribute:: name
223
Armin Ronachered98cac2008-05-07 08:42:11 +0200224 The loading name of the template. If the template was loaded from a
225 string this is `None`.
226
Armin Ronacher5411ce72008-05-25 11:36:22 +0200227 .. attribute:: filename
228
229 The filename of the template on the file system if it was loaded from
230 there. Otherwise this is `None`.
231
Armin Ronachered98cac2008-05-07 08:42:11 +0200232 .. automethod:: render([context])
233
234 .. automethod:: generate([context])
235
236 .. automethod:: stream([context])
Armin Ronacher7259c762008-04-30 13:03:59 +0200237
Armin Ronacherd8326d92016-12-28 22:51:46 +0100238 .. automethod:: render_async([context])
239
240 .. automethod:: generate_async([context])
241
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200242
Armin Ronacher6df604e2008-05-23 22:18:38 +0200243.. autoclass:: jinja2.environment.TemplateStream()
Armin Ronacher74b51062008-06-17 11:28:59 +0200244 :members: disable_buffering, enable_buffering, dump
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200245
246
Armin Ronacher1da23d12010-04-05 18:11:18 +0200247Autoescaping
248------------
249
250.. versionadded:: 2.4
251
252As of Jinja 2.4 the preferred way to do autoescaping is to enable the
253:ref:`autoescape-extension` and to configure a sensible default for
254autoescaping. This makes it possible to enable and disable autoescaping
255on a per-template basis (HTML versus text for instance).
256
257Here a recommended setup that enables autoescaping for templates ending
258in ``'.html'``, ``'.htm'`` and ``'.xml'`` and disabling it by default
259for all other extensions::
260
261 def guess_autoescape(template_name):
262 if template_name is None or '.' not in template_name:
263 return False
264 ext = template_name.rsplit('.', 1)[1]
265 return ext in ('html', 'htm', 'xml')
266
267 env = Environment(autoescape=guess_autoescape,
268 loader=PackageLoader('mypackage'),
269 extensions=['jinja2.ext.autoescape'])
270
271When implementing a guessing autoescape function, make sure you also
272accept `None` as valid template name. This will be passed when generating
273templates from strings.
274
275Inside the templates the behaviour can be temporarily changed by using
276the `autoescape` block (see :ref:`autoescape-overrides`).
277
278
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200279.. _identifier-naming:
280
281Notes on Identifiers
Armin Ronacher5411ce72008-05-25 11:36:22 +0200282--------------------
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200283
284Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to
285match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters
286are currently not allowed. This limitation will probably go away as soon as
287unicode identifiers are fully specified for Python 3.
288
289Filters and tests are looked up in separate namespaces and have slightly
290modified identifier syntax. Filters and tests may contain dots to group
291filters and tests by topic. For example it's perfectly valid to add a
292function into the filter dict and call it `to.unicode`. The regular
293expression for filter and test identifiers is
294``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.
295
296
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200297Undefined Types
298---------------
299
300These classes can be used as undefined types. The :class:`Environment`
301constructor takes an `undefined` parameter that can be one of those classes
302or a custom subclass of :class:`Undefined`. Whenever the template engine is
303unable to look up a name or access an attribute one of those objects is
304created and returned. Some operations on undefined values are then allowed,
305others fail.
306
307The closest to regular Python behavior is the `StrictUndefined` which
308disallows all operations beside testing if it's an undefined object.
309
Armin Ronachera816bf42008-09-17 21:28:01 +0200310.. autoclass:: jinja2.Undefined()
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200311
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200312 .. attribute:: _undefined_hint
313
314 Either `None` or an unicode string with the error message for
315 the undefined object.
316
317 .. attribute:: _undefined_obj
318
319 Either `None` or the owner object that caused the undefined object
320 to be created (for example because an attribute does not exist).
321
322 .. attribute:: _undefined_name
323
324 The name for the undefined variable / attribute or just `None`
325 if no such information exists.
326
327 .. attribute:: _undefined_exception
328
329 The exception that the undefined object wants to raise. This
330 is usually one of :exc:`UndefinedError` or :exc:`SecurityError`.
331
332 .. method:: _fail_with_undefined_error(\*args, \**kwargs)
333
334 When called with any arguments this method raises
335 :attr:`_undefined_exception` with an error message generated
336 from the undefined hints stored on the undefined object.
337
Armin Ronachera816bf42008-09-17 21:28:01 +0200338.. autoclass:: jinja2.DebugUndefined()
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200339
Armin Ronachera816bf42008-09-17 21:28:01 +0200340.. autoclass:: jinja2.StrictUndefined()
Armin Ronacher5411ce72008-05-25 11:36:22 +0200341
Armin Ronacher6e9dfbf2014-06-06 22:14:45 +0600342There is also a factory function that can decorate undefined objects to
343implement logging on failures:
344
345.. autofunction:: jinja2.make_logging_undefined
346
Armin Ronacher5411ce72008-05-25 11:36:22 +0200347Undefined objects are created by calling :attr:`undefined`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200348
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200349.. admonition:: Implementation
350
351 :class:`Undefined` objects are implemented by overriding the special
352 `__underscore__` methods. For example the default :class:`Undefined`
353 class implements `__unicode__` in a way that it returns an empty
354 string, however `__int__` and others still fail with an exception. To
355 allow conversion to int by returning ``0`` you can implement your own::
356
357 class NullUndefined(Undefined):
358 def __int__(self):
359 return 0
360 def __float__(self):
361 return 0.0
362
363 To disallow a method, just override it and raise
Armin Ronacher58f351d2008-05-28 21:30:14 +0200364 :attr:`~Undefined._undefined_exception`. Because this is a very common
365 idom in undefined objects there is the helper method
366 :meth:`~Undefined._fail_with_undefined_error` that does the error raising
367 automatically. Here a class that works like the regular :class:`Undefined`
368 but chokes on iteration::
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200369
370 class NonIterableUndefined(Undefined):
371 __iter__ = Undefined._fail_with_undefined_error
372
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200373
Armin Ronacher7259c762008-04-30 13:03:59 +0200374The Context
375-----------
376
Armin Ronacher6df604e2008-05-23 22:18:38 +0200377.. autoclass:: jinja2.runtime.Context()
Armin Ronacherf35e2812008-05-06 16:04:10 +0200378 :members: resolve, get_exported, get_all
Armin Ronacher7259c762008-04-30 13:03:59 +0200379
380 .. attribute:: parent
381
382 A dict of read only, global variables the template looks up. These
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200383 can either come from another :class:`Context`, from the
Armin Ronacher5411ce72008-05-25 11:36:22 +0200384 :attr:`Environment.globals` or :attr:`Template.globals` or points
385 to a dict created by combining the globals with the variables
386 passed to the render function. It must not be altered.
Armin Ronacher7259c762008-04-30 13:03:59 +0200387
388 .. attribute:: vars
389
390 The template local variables. This list contains environment and
391 context functions from the :attr:`parent` scope as well as local
392 modifications and exported variables from the template. The template
393 will modify this dict during template evaluation but filters and
394 context functions are not allowed to modify it.
395
396 .. attribute:: environment
397
398 The environment that loaded the template.
399
400 .. attribute:: exported_vars
401
402 This set contains all the names the template exports. The values for
403 the names are in the :attr:`vars` dict. In order to get a copy of the
404 exported variables as dict, :meth:`get_exported` can be used.
405
406 .. attribute:: name
407
408 The load name of the template owning this context.
409
410 .. attribute:: blocks
411
412 A dict with the current mapping of blocks in the template. The keys
413 in this dict are the names of the blocks, and the values a list of
414 blocks registered. The last item in each list is the current active
415 block (latest in the inheritance chain).
416
Armin Ronacherfe150f32010-03-15 02:42:41 +0100417 .. attribute:: eval_ctx
418
419 The current :ref:`eval-context`.
420
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200421 .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs)
422
423
424.. admonition:: Implementation
425
426 Context is immutable for the same reason Python's frame locals are
427 immutable inside functions. Both Jinja2 and Python are not using the
428 context / frame locals as data storage for variables but only as primary
429 data source.
430
431 When a template accesses a variable the template does not define, Jinja2
432 looks up the variable in the context, after that the variable is treated
433 as if it was defined in the template.
434
Armin Ronacher7259c762008-04-30 13:03:59 +0200435
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200436.. _loaders:
437
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200438Loaders
439-------
440
441Loaders are responsible for loading templates from a resource such as the
Armin Ronacher7259c762008-04-30 13:03:59 +0200442file system. The environment will keep the compiled modules in memory like
443Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in
444size by default and templates are automatically reloaded.
Armin Ronachercda43df2008-05-03 17:10:05 +0200445All loaders are subclasses of :class:`BaseLoader`. If you want to create your
Armin Ronachercda43df2008-05-03 17:10:05 +0200446own loader, subclass :class:`BaseLoader` and override `get_source`.
447
Armin Ronachera816bf42008-09-17 21:28:01 +0200448.. autoclass:: jinja2.BaseLoader
Armin Ronachercda43df2008-05-03 17:10:05 +0200449 :members: get_source, load
450
451Here a list of the builtin loaders Jinja2 provides:
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200452
Armin Ronachera816bf42008-09-17 21:28:01 +0200453.. autoclass:: jinja2.FileSystemLoader
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200454
Armin Ronachera816bf42008-09-17 21:28:01 +0200455.. autoclass:: jinja2.PackageLoader
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200456
Armin Ronachera816bf42008-09-17 21:28:01 +0200457.. autoclass:: jinja2.DictLoader
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200458
Armin Ronachera816bf42008-09-17 21:28:01 +0200459.. autoclass:: jinja2.FunctionLoader
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200460
Armin Ronachera816bf42008-09-17 21:28:01 +0200461.. autoclass:: jinja2.PrefixLoader
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200462
Armin Ronachera816bf42008-09-17 21:28:01 +0200463.. autoclass:: jinja2.ChoiceLoader
464
Armin Ronacher46844982011-01-29 20:19:58 +0100465.. autoclass:: jinja2.ModuleLoader
466
Armin Ronachera816bf42008-09-17 21:28:01 +0200467
468.. _bytecode-cache:
469
470Bytecode Cache
471--------------
472
473Jinja 2.1 and higher support external bytecode caching. Bytecode caches make
474it possible to store the generated bytecode on the file system or a different
475location to avoid parsing the templates on first use.
476
477This is especially useful if you have a web application that is initialized on
478the first request and Jinja compiles many templates at once which slows down
479the application.
480
Jakub Wilk3fc008b2013-05-25 23:37:34 +0200481To use a bytecode cache, instantiate it and pass it to the :class:`Environment`.
Armin Ronachera816bf42008-09-17 21:28:01 +0200482
483.. autoclass:: jinja2.BytecodeCache
484 :members: load_bytecode, dump_bytecode, clear
485
486.. autoclass:: jinja2.bccache.Bucket
487 :members: write_bytecode, load_bytecode, bytecode_from_string,
488 bytecode_to_string, reset
489
490 .. attribute:: environment
491
492 The :class:`Environment` that created the bucket.
493
494 .. attribute:: key
495
496 The unique cache key for this bucket
497
498 .. attribute:: code
499
500 The bytecode if it's loaded, otherwise `None`.
501
502
503Builtin bytecode caches:
504
505.. autoclass:: jinja2.FileSystemBytecodeCache
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200506
Armin Ronacheraa1d17d2008-09-18 18:09:06 +0200507.. autoclass:: jinja2.MemcachedBytecodeCache
508
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200509
Armin Ronacherd8326d92016-12-28 22:51:46 +0100510Async Support
511-------------
512
513Starting with version 2.9, Jinja2 also supports the Python `async` and
514`await` constructs. As far as template designers go this feature is
515entirely opaque to them however as a developer you should be aware of how
516it's implemented as it influences what type of APIs you can safely expose
517to the template environment.
518
519First you need to be aware that by default async support is disabled as
520enabling it will generate different template code behind the scenes which
521passes everything through the asyncio event loop. This is important to
522understand because it has some impact to what you are doing:
523
524* template rendering will require an event loop to be set for the
525 current thread (``asyncio.get_event_loop`` needs to return one)
526* all template generation code internally runs async generators which
527 means that you will pay a performance penalty even if the non sync
528 methods are used!
529* The sync methods are based on async methods if the async mode is
530 enabled which means that `render` for instance will internally invoke
531 `render_async` and run it as part of the current event loop until the
532 execution finished.
533
534Awaitable objects can be returned from functions in templates and any
535function call in a template will automatically await the result. This
536means that you can let provide a method that asynchronously loads data
537from a database if you so desire and from the template designer's point of
538view this is just another function they can call. This means that the
539``await`` you would normally issue in Python is implied. However this
540only applies to function calls. If an attribute for instance would be an
541avaitable object then this would not result in the expected behavior.
542
543Likewise iterations with a `for` loop support async iterators.
544
Armin Ronachere2535202016-12-31 00:43:50 +0100545.. _policies:
546
547Policies
548--------
549
550Starting with Jinja 2.9 policies can be configured on the environment
551which can slightly influence how filters and other template constructs
552behave. They can be configured with the
553:attr:`~jinja2.Environment.policies` attribute.
554
555Example::
556
557 env.policies['urlize.rel'] = 'nofollow noopener'
558
559``urlize.rel``:
560 A string that defines the items for the `rel` attribute of generated
561 links with the `urlize` filter. These items are always added. The
562 default is `noopener`.
563
564``urlize.target``:
565 The default target that is issued for links from the `urlize` filter
566 if no other target is defined by the call explicitly.
567
Armin Ronachere71a1302017-01-06 21:33:51 +0100568``json.dumps_function``:
569 If this is set to a value other than `None` then the `tojson` filter
570 will dump with this function instead of the default one. Note that
571 this function should accept arbitrary extra arguments which might be
572 passed in the future from the filter. Currently the only argument
573 that might be passed is `indent`. The default dump function is
574 ``json.dumps``.
575
576``json.dumps_kwargs``:
577 Keyword arguments to be passed to the dump function. The default is
578 ``{'sort_keys': True}``.
579
Armin Ronacherd8326d92016-12-28 22:51:46 +0100580
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200581Utilities
582---------
583
584These helper functions and classes are useful if you add custom filters or
585functions to a Jinja2 environment.
586
Armin Ronachera816bf42008-09-17 21:28:01 +0200587.. autofunction:: jinja2.environmentfilter
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200588
Armin Ronachera816bf42008-09-17 21:28:01 +0200589.. autofunction:: jinja2.contextfilter
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200590
Armin Ronacherfe150f32010-03-15 02:42:41 +0100591.. autofunction:: jinja2.evalcontextfilter
592
Armin Ronachera816bf42008-09-17 21:28:01 +0200593.. autofunction:: jinja2.environmentfunction
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200594
Armin Ronachera816bf42008-09-17 21:28:01 +0200595.. autofunction:: jinja2.contextfunction
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200596
Armin Ronacherfe150f32010-03-15 02:42:41 +0100597.. autofunction:: jinja2.evalcontextfunction
598
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200599.. function:: escape(s)
600
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200601 Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s`
602 to HTML-safe sequences. Use this if you need to display text that might
603 contain such characters in HTML. This function will not escaped objects
604 that do have an HTML representation such as already escaped data.
605
606 The return value is a :class:`Markup` string.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200607
Armin Ronachera816bf42008-09-17 21:28:01 +0200608.. autofunction:: jinja2.clear_caches
Armin Ronacher187bde12008-05-01 18:19:16 +0200609
Armin Ronachera816bf42008-09-17 21:28:01 +0200610.. autofunction:: jinja2.is_undefined
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200611
Armin Ronachera816bf42008-09-17 21:28:01 +0200612.. autoclass:: jinja2.Markup([string])
Armin Ronacher58f351d2008-05-28 21:30:14 +0200613 :members: escape, unescape, striptags
614
615.. admonition:: Note
616
617 The Jinja2 :class:`Markup` class is compatible with at least Pylons and
618 Genshi. It's expected that more template engines and framework will pick
619 up the `__html__` concept soon.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200620
621
622Exceptions
623----------
624
Armin Ronachera816bf42008-09-17 21:28:01 +0200625.. autoexception:: jinja2.TemplateError
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200626
Armin Ronachera816bf42008-09-17 21:28:01 +0200627.. autoexception:: jinja2.UndefinedError
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200628
Armin Ronachera816bf42008-09-17 21:28:01 +0200629.. autoexception:: jinja2.TemplateNotFound
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200630
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100631.. autoexception:: jinja2.TemplatesNotFound
632
Armin Ronachera816bf42008-09-17 21:28:01 +0200633.. autoexception:: jinja2.TemplateSyntaxError
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200634
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200635 .. attribute:: message
636
637 The error message as utf-8 bytestring.
638
639 .. attribute:: lineno
640
641 The line number where the error occurred
642
643 .. attribute:: name
644
645 The load name for the template as unicode string.
646
647 .. attribute:: filename
648
649 The filename that loaded the template as bytestring in the encoding
650 of the file system (most likely utf-8 or mbcs on Windows systems).
651
652 The reason why the filename and error message are bytestrings and not
653 unicode strings is that Python 2.x is not using unicode for exceptions
654 and tracebacks as well as the compiler. This will change with Python 3.
655
Armin Ronachera816bf42008-09-17 21:28:01 +0200656.. autoexception:: jinja2.TemplateAssertionError
Armin Ronacher7259c762008-04-30 13:03:59 +0200657
658
659.. _writing-filters:
660
661Custom Filters
662--------------
663
664Custom filters are just regular Python functions that take the left side of
Guillaume Paumier345e0ba2016-04-10 08:58:06 -0700665the filter as first argument and the arguments passed to the filter as
Armin Ronacher7259c762008-04-30 13:03:59 +0200666extra arguments or keyword arguments.
667
668For example in the filter ``{{ 42|myfilter(23) }}`` the function would be
669called with ``myfilter(42, 23)``. Here for example a simple filter that can
670be applied to datetime objects to format them::
671
672 def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
673 return value.strftime(format)
674
675You can register it on the template environment by updating the
676:attr:`~Environment.filters` dict on the environment::
677
678 environment.filters['datetimeformat'] = datetimeformat
679
680Inside the template it can then be used as follows:
681
682.. sourcecode:: jinja
683
684 written on: {{ article.pub_date|datetimeformat }}
685 publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}
686
687Filters can also be passed the current template context or environment. This
Armin Ronacher0aa0f582009-03-18 01:01:36 +0100688is useful if a filter wants to return an undefined value or check the current
Armin Ronacher2e3c9c72010-04-10 13:03:46 +0200689:attr:`~Environment.autoescape` setting. For this purpose three decorators
Armin Ronacherfe150f32010-03-15 02:42:41 +0100690exist: :func:`environmentfilter`, :func:`contextfilter` and
691:func:`evalcontextfilter`.
Armin Ronacher7259c762008-04-30 13:03:59 +0200692
693Here a small example filter that breaks a text into HTML line breaks and
694paragraphs and marks the return value as safe HTML string if autoescaping is
695enabled::
696
697 import re
Jeffrey Finkelstein449ef022011-07-01 15:46:54 -0700698 from jinja2 import evalcontextfilter, Markup, escape
Armin Ronacher7259c762008-04-30 13:03:59 +0200699
700 _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
701
Armin Ronacherfe150f32010-03-15 02:42:41 +0100702 @evalcontextfilter
703 def nl2br(eval_ctx, value):
Jörn Hees17024512014-06-15 18:31:16 +0200704 result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', Markup('<br>\n'))
Armin Ronacher7259c762008-04-30 13:03:59 +0200705 for p in _paragraph_re.split(escape(value)))
Armin Ronacherfe150f32010-03-15 02:42:41 +0100706 if eval_ctx.autoescape:
Armin Ronacher7259c762008-04-30 13:03:59 +0200707 result = Markup(result)
708 return result
709
710Context filters work the same just that the first argument is the current
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200711active :class:`Context` rather then the environment.
Armin Ronacher7259c762008-04-30 13:03:59 +0200712
713
Armin Ronacherfe150f32010-03-15 02:42:41 +0100714.. _eval-context:
715
716Evaluation Context
717------------------
718
719The evaluation context (short eval context or eval ctx) is a new object
Jakub Wilk3fc008b2013-05-25 23:37:34 +0200720introduced in Jinja 2.4 that makes it possible to activate and deactivate
Armin Ronacherfe150f32010-03-15 02:42:41 +0100721compiled features at runtime.
722
723Currently it is only used to enable and disable the automatic escaping but
724can be used for extensions as well.
725
726In previous Jinja versions filters and functions were marked as
727environment callables in order to check for the autoescape status from the
728environment. In new versions it's encouraged to check the setting from the
729evaluation context instead.
730
731Previous versions::
732
733 @environmentfilter
734 def filter(env, value):
735 result = do_something(value)
736 if env.autoescape:
737 result = Markup(result)
738 return result
739
740In new versions you can either use a :func:`contextfilter` and access the
741evaluation context from the actual context, or use a
742:func:`evalcontextfilter` which directly passes the evaluation context to
743the function::
744
745 @contextfilter
746 def filter(context, value):
747 result = do_something(value)
748 if context.eval_ctx.autoescape:
749 result = Markup(result)
750 return result
751
752 @evalcontextfilter
753 def filter(eval_ctx, value):
754 result = do_something(value)
755 if eval_ctx.autoescape:
756 result = Markup(result)
757 return result
758
759The evaluation context must not be modified at runtime. Modifications
760must only happen with a :class:`nodes.EvalContextModifier` and
761:class:`nodes.ScopedEvalContextModifier` from an extension, not on the
762eval context object itself.
763
Armin Ronacher76ae15e2010-03-15 09:36:47 +0100764.. autoclass:: jinja2.nodes.EvalContext
Armin Ronacher30fda272010-03-15 03:06:04 +0100765
766 .. attribute:: autoescape
767
768 `True` or `False` depending on if autoescaping is active or not.
769
770 .. attribute:: volatile
771
772 `True` if the compiler cannot evaluate some expressions at compile
773 time. At runtime this should always be `False`.
774
775
Armin Ronacher7259c762008-04-30 13:03:59 +0200776.. _writing-tests:
777
778Custom Tests
779------------
780
Armin Ronachera5d8f552008-09-11 20:46:34 +0200781Tests work like filters just that there is no way for a test to get access
Armin Ronacher7259c762008-04-30 13:03:59 +0200782to the environment or context and that they can't be chained. The return
Armin Ronachera5d8f552008-09-11 20:46:34 +0200783value of a test should be `True` or `False`. The purpose of a test is to
Armin Ronacher7259c762008-04-30 13:03:59 +0200784give the template designers the possibility to perform type and conformability
785checks.
786
Armin Ronachera5d8f552008-09-11 20:46:34 +0200787Here a simple test that checks if a variable is a prime number::
Armin Ronacher7259c762008-04-30 13:03:59 +0200788
789 import math
790
791 def is_prime(n):
792 if n == 2:
793 return True
794 for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1):
795 if n % i == 0:
796 return False
797 return True
798
799
800You can register it on the template environment by updating the
801:attr:`~Environment.tests` dict on the environment::
802
803 environment.tests['prime'] = is_prime
804
805A template designer can then use the test like this:
806
807.. sourcecode:: jinja
808
809 {% if 42 is prime %}
810 42 is a prime number
811 {% else %}
812 42 is not a prime number
813 {% endif %}
814
815
816.. _global-namespace:
817
818The Global Namespace
819--------------------
820
Armin Ronacher981cbf62008-05-13 09:12:27 +0200821Variables stored in the :attr:`Environment.globals` dict are special as they
822are available for imported templates too, even if they are imported without
823context. This is the place where you can put variables and functions
824that should be available all the time. Additionally :attr:`Template.globals`
825exist that are variables available to a specific template that are available
826to all :meth:`~Template.render` calls.
Armin Ronacher5411ce72008-05-25 11:36:22 +0200827
828
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200829.. _low-level-api:
830
Armin Ronacher5411ce72008-05-25 11:36:22 +0200831Low Level API
832-------------
833
834The low level API exposes functionality that can be useful to understand some
835implementation details, debugging purposes or advanced :ref:`extension
Armin Ronacher61a5a242008-05-26 12:07:44 +0200836<jinja-extensions>` techniques. Unless you know exactly what you are doing we
837don't recommend using any of those.
Armin Ronacher5411ce72008-05-25 11:36:22 +0200838
839.. automethod:: Environment.lex
840
841.. automethod:: Environment.parse
842
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200843.. automethod:: Environment.preprocess
844
Armin Ronacher5411ce72008-05-25 11:36:22 +0200845.. automethod:: Template.new_context
846
847.. method:: Template.root_render_func(context)
848
849 This is the low level render function. It's passed a :class:`Context`
850 that has to be created by :meth:`new_context` of the same template or
851 a compatible template. This render function is generated by the
852 compiler from the template code and returns a generator that yields
853 unicode strings.
854
855 If an exception in the template code happens the template engine will
856 not rewrite the exception but pass through the original one. As a
857 matter of fact this function should only be called from within a
858 :meth:`render` / :meth:`generate` / :meth:`stream` call.
859
860.. attribute:: Template.blocks
861
862 A dict of block render functions. Each of these functions works exactly
863 like the :meth:`root_render_func` with the same limitations.
864
865.. attribute:: Template.is_up_to_date
866
867 This attribute is `False` if there is a newer version of the template
868 available, otherwise `True`.
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200869
870.. admonition:: Note
871
Armin Ronacher58f351d2008-05-28 21:30:14 +0200872 The low-level API is fragile. Future Jinja2 versions will try not to
873 change it in a backwards incompatible way but modifications in the Jinja2
874 core may shine through. For example if Jinja2 introduces a new AST node
875 in later versions that may be returned by :meth:`~Environment.parse`.
Armin Ronacher63cf9b82009-07-26 10:33:36 +0200876
877The Meta API
878------------
879
880.. versionadded:: 2.2
881
882The meta API returns some information about abstract syntax trees that
883could help applications to implement more advanced template concepts. All
884the functions of the meta API operate on an abstract syntax tree as
885returned by the :meth:`Environment.parse` method.
886
887.. autofunction:: jinja2.meta.find_undeclared_variables
888
889.. autofunction:: jinja2.meta.find_referenced_templates