blob: 0825fd4f9b7343afefff38bab60c3bdaadfe6067 [file] [log] [blame]
Armin Ronachered98cac2008-05-07 08:42:11 +02001.. _jinja-extensions:
2
3Extensions
4==========
5
Armin Ronachered98cac2008-05-07 08:42:11 +02006Jinja2 supports extensions that can add extra filters, tests, globals or even
Lucian Ursu07497dc2013-11-29 14:16:06 +02007extend the parser. The main motivation of extensions is to move often used
Armin Ronachered98cac2008-05-07 08:42:11 +02008code into a reusable class like adding support for internationalization.
9
10
11Adding Extensions
12-----------------
13
14Extensions are added to the Jinja2 environment at creation time. Once the
15environment is created additional extensions cannot be added. To add an
16extension pass a list of extension classes or import paths to the
Lucian Ursu07497dc2013-11-29 14:16:06 +020017`extensions` parameter of the :class:`Environment` constructor. The following
Armin Ronachered98cac2008-05-07 08:42:11 +020018example creates a Jinja2 environment with the i18n extension loaded::
19
Armin Ronacher09c002e2008-05-10 22:21:30 +020020 jinja_env = Environment(extensions=['jinja2.ext.i18n'])
Armin Ronachered98cac2008-05-07 08:42:11 +020021
22
Armin Ronachered98cac2008-05-07 08:42:11 +020023.. _i18n-extension:
24
Armin Ronacher023b5e92008-05-08 11:03:10 +020025i18n Extension
26--------------
Armin Ronachered98cac2008-05-07 08:42:11 +020027
Armin Ronacher5d2733f2008-05-15 23:26:52 +020028**Import name:** `jinja2.ext.i18n`
29
Chad Whitacree53659d2015-02-05 14:53:19 -050030The i18n extension can be used in combination with `gettext`_ or `babel`_. If
31the i18n extension is enabled Jinja2 provides a `trans` statement that marks
32the wrapped string as translatable and calls `gettext`.
Armin Ronachered98cac2008-05-07 08:42:11 +020033
Lucian Ursu07497dc2013-11-29 14:16:06 +020034After enabling, dummy `_` function that forwards calls to `gettext` is added
Armin Ronacher762079c2008-05-08 23:57:56 +020035to the environment globals. An internationalized application then has to
Lucian Ursu07497dc2013-11-29 14:16:06 +020036provide a `gettext` function and optionally an `ngettext` function into the
37namespace, either globally or for each rendering.
Armin Ronacher762079c2008-05-08 23:57:56 +020038
Armin Ronacherffaa2e72010-05-29 20:57:16 +020039Environment Methods
40~~~~~~~~~~~~~~~~~~~
41
Lucian Ursu07497dc2013-11-29 14:16:06 +020042After enabling the extension, the environment provides the following
Armin Ronacher762079c2008-05-08 23:57:56 +020043additional methods:
44
Armin Ronacherffaa2e72010-05-29 20:57:16 +020045.. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)
Armin Ronacher762079c2008-05-08 23:57:56 +020046
Lucian Ursu07497dc2013-11-29 14:16:06 +020047 Installs a translation globally for that environment. The translations
Armin Ronacher762079c2008-05-08 23:57:56 +020048 object provided must implement at least `ugettext` and `ungettext`.
49 The `gettext.NullTranslations` and `gettext.GNUTranslations` classes
50 as well as `Babel`_\s `Translations` class are supported.
51
Armin Ronacherffaa2e72010-05-29 20:57:16 +020052 .. versionchanged:: 2.5 newstyle gettext added
53
54.. method:: jinja2.Environment.install_null_translations(newstyle=False)
Armin Ronacher762079c2008-05-08 23:57:56 +020055
56 Install dummy gettext functions. This is useful if you want to prepare
57 the application for internationalization but don't want to implement the
58 full internationalization system yet.
59
Armin Ronacherffaa2e72010-05-29 20:57:16 +020060 .. versionchanged:: 2.5 newstyle gettext added
61
62.. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False)
63
64 Installs the given `gettext` and `ngettext` callables into the
65 environment as globals. They are supposed to behave exactly like the
66 standard library's :func:`gettext.ugettext` and
67 :func:`gettext.ungettext` functions.
68
69 If `newstyle` is activated, the callables are wrapped to work like
70 newstyle callables. See :ref:`newstyle-gettext` for more information.
71
72 .. versionadded:: 2.5
73
Armin Ronacher762079c2008-05-08 23:57:56 +020074.. method:: jinja2.Environment.uninstall_gettext_translations()
75
76 Uninstall the translations again.
77
78.. method:: jinja2.Environment.extract_translations(source)
79
80 Extract localizable strings from the given template node or source.
81
82 For every string found this function yields a ``(lineno, function,
83 message)`` tuple, where:
84
85 * `lineno` is the number of the line on which the string was found,
86 * `function` is the name of the `gettext` function used (if the
87 string was extracted from embedded Python code), and
88 * `message` is the string itself (a `unicode` object, or a tuple
89 of `unicode` objects for functions with multiple string arguments).
90
Lucian Ursu07497dc2013-11-29 14:16:06 +020091 If `Babel`_ is installed, :ref:`the babel integration <babel-integration>`
Armin Ronacher762079c2008-05-08 23:57:56 +020092 can be used to extract strings for babel.
Armin Ronachered98cac2008-05-07 08:42:11 +020093
94For a web application that is available in multiple languages but gives all
95the users the same language (for example a multilingual forum software
96installed for a French community) may load the translations once and add the
97translation methods to the environment at environment generation time::
98
99 translations = get_gettext_translations()
Armin Ronacher2b228742008-05-18 20:29:32 +0200100 env = Environment(extensions=['jinja2.ext.i18n'])
Armin Ronacher762079c2008-05-08 23:57:56 +0200101 env.install_gettext_translations(translations)
Armin Ronachered98cac2008-05-07 08:42:11 +0200102
103The `get_gettext_translations` function would return the translator for the
Armin Ronacher762079c2008-05-08 23:57:56 +0200104current configuration. (For example by using `gettext.find`)
Armin Ronachered98cac2008-05-07 08:42:11 +0200105
106The usage of the `i18n` extension for template designers is covered as part
107:ref:`of the template documentation <i18n-in-templates>`.
108
Armin Ronachered98cac2008-05-07 08:42:11 +0200109.. _gettext: http://docs.python.org/dev/library/gettext
Armin Ronacher762079c2008-05-08 23:57:56 +0200110.. _Babel: http://babel.edgewall.org/
Armin Ronachered98cac2008-05-07 08:42:11 +0200111
Armin Ronacherffaa2e72010-05-29 20:57:16 +0200112.. _newstyle-gettext:
113
114Newstyle Gettext
115~~~~~~~~~~~~~~~~
116
117.. versionadded:: 2.5
118
119Starting with version 2.5 you can use newstyle gettext calls. These are
120inspired by trac's internal gettext functions and are fully supported by
121the babel extraction tool. They might not work as expected by other
122extraction tools in case you are not using Babel's.
123
124What's the big difference between standard and newstyle gettext calls? In
125general they are less to type and less error prone. Also if they are used
126in an autoescaping environment they better support automatic escaping.
Lucian Ursu07497dc2013-11-29 14:16:06 +0200127Here are some common differences between old and new calls:
Armin Ronacherffaa2e72010-05-29 20:57:16 +0200128
129standard gettext:
130
131.. sourcecode:: html+jinja
132
133 {{ gettext('Hello World!') }}
134 {{ gettext('Hello %(name)s!')|format(name='World') }}
135 {{ ngettext('%(num)d apple', '%(num)d apples', apples|count)|format(
136 num=apples|count
137 )}}
138
139newstyle gettext looks like this instead:
140
141.. sourcecode:: html+jinja
142
143 {{ gettext('Hello World!') }}
144 {{ gettext('Hello %(name)s!', name='World') }}
145 {{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }}
146
Lucian Ursu07497dc2013-11-29 14:16:06 +0200147The advantages of newstyle gettext are that you have less to type and that
Armin Ronacherffaa2e72010-05-29 20:57:16 +0200148named placeholders become mandatory. The latter sounds like a
149disadvantage but solves a lot of troubles translators are often facing
150when they are unable to switch the positions of two placeholder. With
151newstyle gettext, all format strings look the same.
152
153Furthermore with newstyle gettext, string formatting is also used if no
154placeholders are used which makes all strings behave exactly the same.
155Last but not least are newstyle gettext calls able to properly mark
156strings for autoescaping which solves lots of escaping related issues many
157templates are experiencing over time when using autoescaping.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200158
Armin Ronacher6df604e2008-05-23 22:18:38 +0200159Expression Statement
160--------------------
Armin Ronacher5d2733f2008-05-15 23:26:52 +0200161
162**Import name:** `jinja2.ext.do`
163
Armin Ronacher6df604e2008-05-23 22:18:38 +0200164The "do" aka expression-statement extension adds a simple `do` tag to the
Armin Ronacher5d2733f2008-05-15 23:26:52 +0200165template engine that works like a variable expression but ignores the
166return value.
167
Armin Ronacher3da90312008-05-23 16:37:28 +0200168.. _loopcontrols-extension:
169
Armin Ronacher6df604e2008-05-23 22:18:38 +0200170Loop Controls
171-------------
Armin Ronacher3da90312008-05-23 16:37:28 +0200172
173**Import name:** `jinja2.ext.loopcontrols`
174
175This extension adds support for `break` and `continue` in loops. After
Lucian Ursu07497dc2013-11-29 14:16:06 +0200176enabling, Jinja2 provides those two keywords which work exactly like in
Armin Ronacher3da90312008-05-23 16:37:28 +0200177Python.
178
Armin Ronacher9b4cc9f2010-02-07 03:55:15 +0100179.. _with-extension:
180
181With Statement
182--------------
183
184**Import name:** `jinja2.ext.with_`
185
186.. versionadded:: 2.3
187
188This extension adds support for the with keyword. Using this keyword it
189is possible to enforce a nested scope in a template. Variables can be
190declared directly in the opening block of the with statement or using a
191standard `set` statement directly within.
192
Armin Ronacherfe150f32010-03-15 02:42:41 +0100193.. _autoescape-extension:
194
195Autoescape Extension
196--------------------
197
198**Import name:** `jinja2.ext.autoescape`
199
200.. versionadded:: 2.4
201
202The autoescape extension allows you to toggle the autoescape feature from
203within the template. If the environment's :attr:`~Environment.autoescape`
204setting is set to `False` it can be activated, if it's `True` it can be
Armin Ronacherfd729722010-08-16 12:13:04 +0200205deactivated. The setting overriding is scoped.
Armin Ronacherfe150f32010-03-15 02:42:41 +0100206
Armin Ronacher5d2733f2008-05-15 23:26:52 +0200207
Armin Ronachered98cac2008-05-07 08:42:11 +0200208.. _writing-extensions:
209
210Writing Extensions
211------------------
212
Armin Ronacher762079c2008-05-08 23:57:56 +0200213.. module:: jinja2.ext
214
Jakub Wilk3fc008b2013-05-25 23:37:34 +0200215By writing extensions you can add custom tags to Jinja2. This is a non-trivial
Armin Ronacher023b5e92008-05-08 11:03:10 +0200216task and usually not needed as the default tags and expressions cover all
217common use cases. The i18n extension is a good example of why extensions are
Lucian Ursu07497dc2013-11-29 14:16:06 +0200218useful. Another one would be fragment caching.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200219
Armin Ronacherb9e78752008-05-10 23:36:28 +0200220When writing extensions you have to keep in mind that you are working with the
Oliver Beattie6e97b062011-12-15 09:47:34 +0000221Jinja2 template compiler which does not validate the node tree you are passing
Armin Ronacherb9e78752008-05-10 23:36:28 +0200222to it. If the AST is malformed you will get all kinds of compiler or runtime
223errors that are horrible to debug. Always make sure you are using the nodes
224you create correctly. The API documentation below shows which nodes exist and
225how to use them.
226
Armin Ronacher023b5e92008-05-08 11:03:10 +0200227Example Extension
228~~~~~~~~~~~~~~~~~
229
Armin Ronacher762079c2008-05-08 23:57:56 +0200230The following example implements a `cache` tag for Jinja2 by using the
231`Werkzeug`_ caching contrib module:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200232
233.. literalinclude:: cache_extension.py
234 :language: python
235
Armin Ronacher762079c2008-05-08 23:57:56 +0200236And here is how you use it in an environment::
Armin Ronacher023b5e92008-05-08 11:03:10 +0200237
238 from jinja2 import Environment
239 from werkzeug.contrib.cache import SimpleCache
240
Armin Ronacher762079c2008-05-08 23:57:56 +0200241 env = Environment(extensions=[FragmentCacheExtension])
242 env.fragment_cache = SimpleCache()
Armin Ronacher023b5e92008-05-08 11:03:10 +0200243
Armin Ronacher6df604e2008-05-23 22:18:38 +0200244Inside the template it's then possible to mark blocks as cacheable. The
245following example caches a sidebar for 300 seconds:
246
247.. sourcecode:: html+jinja
248
249 {% cache 'sidebar', 300 %}
250 <div class="sidebar">
251 ...
252 </div>
253 {% endcache %}
254
Armin Ronacher023b5e92008-05-08 11:03:10 +0200255.. _Werkzeug: http://werkzeug.pocoo.org/
256
257Extension API
258~~~~~~~~~~~~~
259
260Extensions always have to extend the :class:`jinja2.ext.Extension` class:
261
262.. autoclass:: Extension
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200263 :members: preprocess, filter_stream, parse, attr, call_method
Armin Ronacher023b5e92008-05-08 11:03:10 +0200264
265 .. attribute:: identifier
266
267 The identifier of the extension. This is always the true import name
268 of the extension class and must not be changed.
269
270 .. attribute:: tags
271
272 If the extension implements custom tags this is a set of tag names
273 the extension is listening for.
274
275Parser API
276~~~~~~~~~~
277
278The parser passed to :meth:`Extension.parse` provides ways to parse
279expressions of different types. The following methods may be used by
280extensions:
281
282.. autoclass:: jinja2.parser.Parser
Armin Ronacher09c002e2008-05-10 22:21:30 +0200283 :members: parse_expression, parse_tuple, parse_assign_target,
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200284 parse_statements, free_identifier, fail
Armin Ronacher023b5e92008-05-08 11:03:10 +0200285
286 .. attribute:: filename
287
288 The filename of the template the parser processes. This is **not**
Armin Ronacher67fdddf2008-05-16 09:27:51 +0200289 the load name of the template. For the load name see :attr:`name`.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200290 For templates that were not loaded form the file system this is
291 `None`.
292
Armin Ronacher67fdddf2008-05-16 09:27:51 +0200293 .. attribute:: name
294
295 The load name of the template.
296
Armin Ronacher023b5e92008-05-08 11:03:10 +0200297 .. attribute:: stream
298
299 The current :class:`~jinja2.lexer.TokenStream`
300
301.. autoclass:: jinja2.lexer.TokenStream
Armin Ronacherfdf95302008-05-11 22:20:51 +0200302 :members: push, look, eos, skip, next, next_if, skip_if, expect
Armin Ronacher023b5e92008-05-08 11:03:10 +0200303
304 .. attribute:: current
305
306 The current :class:`~jinja2.lexer.Token`.
307
308.. autoclass:: jinja2.lexer.Token
309 :members: test, test_any
310
311 .. attribute:: lineno
312
313 The line number of the token
314
315 .. attribute:: type
316
317 The type of the token. This string is interned so you may compare
318 it with arbitrary strings using the `is` operator.
319
320 .. attribute:: value
321
322 The value of the token.
323
Armin Ronacherd02fc7d2008-06-14 14:19:47 +0200324There is also a utility function in the lexer module that can count newline
325characters in strings:
326
327.. autofunction:: jinja2.lexer.count_newlines
328
Armin Ronacher023b5e92008-05-08 11:03:10 +0200329AST
330~~~
331
332The AST (Abstract Syntax Tree) is used to represent a template after parsing.
333It's build of nodes that the compiler then converts into executable Python
334code objects. Extensions that provide custom statements can return nodes to
335execute custom Python code.
336
337The list below describes all nodes that are currently available. The AST may
338change between Jinja2 versions but will stay backwards compatible.
339
340For more information have a look at the repr of :meth:`jinja2.Environment.parse`.
341
342.. module:: jinja2.nodes
343
344.. jinjanodes::
345
346.. autoexception:: Impossible