Debian Codegraph @

docs/extensions.rst

raw
1 .. _jinja-extensions:
2
3 Extensions
4 ==========
5
6 Jinja supports extensions that can add extra filters, tests, globals or even
7 extend the parser. The main motivation of extensions is to move often used
8 code into a reusable class like adding support for internationalization.
9
10
11 Adding Extensions
12 -----------------
13
14 Extensions are added to the Jinja environment at creation time. To add an
15 extension pass a list of extension classes or import paths to the
16 ``extensions`` parameter of the :class:`~jinja2.Environment` constructor. The following
17 example creates a Jinja environment with the i18n extension loaded::
18
19 jinja_env = Environment(extensions=['jinja2.ext.i18n'])
20
21 To add extensions after creation time, use the :meth:`~jinja2.Environment.add_extension` method::
22
23 jinja_env.add_extension('jinja2.ext.debug')
24
25
26 .. _i18n-extension:
27
28 i18n Extension
29 --------------
30
31 **Import name:** ``jinja2.ext.i18n``
32
33 The i18n extension can be used in combination with `gettext`_ or
34 `Babel`_. When it's enabled, Jinja provides a ``trans`` statement that
35 marks a block as translatable and calls ``gettext``.
36
37 After enabling, an application has to provide functions for ``gettext``,
38 ``ngettext``, and optionally ``pgettext`` and ``npgettext``, either
39 globally or when rendering. A ``_()`` function is added as an alias to
40 the ``gettext`` function.
41
42 A convenient way to provide these functions is to call one of the below
43 methods depending on the translation system in use. If you do not require
44 actual translation, use ``Environment.install_null_translations`` to
45 install no-op functions.
46
47 Environment Methods
48 ~~~~~~~~~~~~~~~~~~~
49
50 After enabling the extension, the environment provides the following
51 additional methods:
52
53 .. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)
54
55 Installs a translation globally for the environment. The
56 ``translations`` object must implement ``gettext``, ``ngettext``,
57 and optionally ``pgettext`` and ``npgettext``.
58 :class:`gettext.NullTranslations`, :class:`gettext.GNUTranslations`,
59 and `Babel`_\s ``Translations`` are supported.
60
61 .. versionchanged:: 3.0
62 Added ``pgettext`` and ``npgettext``.
63
64 .. versionchanged:: 2.5
65 Added new-style gettext support.
66
67 .. method:: jinja2.Environment.install_null_translations(newstyle=False)
68
69 Install no-op gettext functions. This is useful if you want to
70 prepare the application for internationalization but don't want to
71 implement the full system yet.
72
73 .. versionchanged:: 2.5 Added new-style gettext support.
74
75 .. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False, pgettext=None, npgettext=None)
76
77 Install the given ``gettext``, ``ngettext``, ``pgettext``, and
78 ``npgettext`` callables into the environment. They should behave
79 exactly like :func:`gettext.gettext`, :func:`gettext.ngettext`,
80 :func:`gettext.pgettext` and :func:`gettext.npgettext`.
81
82 If ``newstyle`` is activated, the callables are wrapped to work like
83 newstyle callables. See :ref:`newstyle-gettext` for more information.
84
85 .. versionchanged:: 3.0
86 Added ``pgettext`` and ``npgettext``.
87
88 .. versionadded:: 2.5
89 Added new-style gettext support.
90
91 .. method:: jinja2.Environment.uninstall_gettext_translations()
92
93 Uninstall the environment's globally installed translation.
94
95 .. method:: jinja2.Environment.extract_translations(source)
96
97 Extract localizable strings from the given template node or source.
98
99 For every string found this function yields a ``(lineno, function,
100 message)`` tuple, where:
101
102 - ``lineno`` is the number of the line on which the string was
103 found.
104 - ``function`` is the name of the ``gettext`` function used (if
105 the string was extracted from embedded Python code).
106 - ``message`` is the string itself, or a tuple of strings for
107 functions with multiple arguments.
108
109 If `Babel`_ is installed, see :ref:`babel-integration` to extract
110 the strings.
111
112 For a web application that is available in multiple languages but gives
113 all the users the same language (for example, multilingual forum
114 software installed for a French community), the translation may be
115 installed when the environment is created.
116
117 .. code-block:: python
118
119 translations = get_gettext_translations()
120 env = Environment(extensions=["jinja2.ext.i18n"])
121 env.install_gettext_translations(translations)
122
123 The ``get_gettext_translations`` function would return the translator
124 for the current configuration, for example by using ``gettext.find``.
125
126 The usage of the ``i18n`` extension for template designers is covered in
127 :ref:`the template documentation <i18n-in-templates>`.
128
129 .. _gettext: https://docs.python.org/3/library/gettext.html
130 .. _Babel: https://babel.pocoo.org/
131
132
133 Whitespace Trimming
134 ~~~~~~~~~~~~~~~~~~~
135
136 .. versionadded:: 2.10
137
138 Within ``{% trans %}`` blocks, it can be useful to trim line breaks and
139 whitespace so that the block of text looks like a simple string with
140 single spaces in the translation file.
141
142 Linebreaks and surrounding whitespace can be automatically trimmed by
143 enabling the ``ext.i18n.trimmed`` :ref:`policy <ext-i18n-trimmed>`.
144
145
146 .. _newstyle-gettext:
147
148 New Style Gettext
149 ~~~~~~~~~~~~~~~~~
150
151 .. versionadded:: 2.5
152
153 New style gettext calls are less to type, less error prone, and support
154 autoescaping better.
155
156 You can use "new style" gettext calls by setting
157 ``env.newstyle_gettext = True`` or passing ``newstyle=True`` to
158 ``env.install_translations``. They are fully supported by the Babel
159 extraction tool, but might not work as expected with other extraction
160 tools.
161
162 With standard ``gettext`` calls, string formatting is a separate step
163 done with the ``|format`` filter. This requires duplicating work for
164 ``ngettext`` calls.
165
166 .. sourcecode:: jinja
167
168 {{ gettext("Hello, World!") }}
169 {{ gettext("Hello, %(name)s!")|format(name=name) }}
170 {{ ngettext(
171 "%(num)d apple", "%(num)d apples", apples|count
172 )|format(num=apples|count) }}
173 {{ pgettext("greeting", "Hello, World!") }}
174 {{ npgettext(
175 "fruit", "%(num)d apple", "%(num)d apples", apples|count
176 )|format(num=apples|count) }}
177
178 New style ``gettext`` make formatting part of the call, and behind the
179 scenes enforce more consistency.
180
181 .. sourcecode:: jinja
182
183 {{ gettext("Hello, World!") }}
184 {{ gettext("Hello, %(name)s!", name=name) }}
185 {{ ngettext("%(num)d apple", "%(num)d apples", apples|count) }}
186 {{ pgettext("greeting", "Hello, World!") }}
187 {{ npgettext("fruit", "%(num)d apple", "%(num)d apples", apples|count) }}
188
189 The advantages of newstyle gettext are:
190
191 - There's no separate formatting step, you don't have to remember to
192 use the ``|format`` filter.
193 - Only named placeholders are allowed. This solves a common problem
194 translators face because positional placeholders can't switch
195 positions meaningfully. Named placeholders always carry semantic
196 information about what value goes where.
197 - String formatting is used even if no placeholders are used, which
198 makes all strings use a consistent format. Remember to escape any
199 raw percent signs as ``%%``, such as ``100%%``.
200 - The translated string is marked safe, formatting performs escaping
201 as needed. Mark a parameter as ``|safe`` if it has already been
202 escaped.
203
204
205 Expression Statement
206 --------------------
207
208 **Import name:** ``jinja2.ext.do``
209
210 The "do" aka expression-statement extension adds a simple ``do`` tag to the
211 template engine that works like a variable expression but ignores the
212 return value.
213
214 .. _loopcontrols-extension:
215
216 Loop Controls
217 -------------
218
219 **Import name:** ``jinja2.ext.loopcontrols``
220
221 This extension adds support for ``break`` and ``continue`` in loops. After
222 enabling, Jinja provides those two keywords which work exactly like in
223 Python.
224
225 .. _with-extension:
226
227 With Statement
228 --------------
229
230 **Import name:** ``jinja2.ext.with_``
231
232 .. versionchanged:: 2.9
233
234 This extension is now built-in and no longer does anything.
235
236 .. _autoescape-extension:
237
238 Autoescape Extension
239 --------------------
240
241 **Import name:** ``jinja2.ext.autoescape``
242
243 .. versionchanged:: 2.9
244
245 This extension was removed and is now built-in. Enabling the
246 extension no longer does anything.
247
248
249 .. _debug-extension:
250
251 Debug Extension
252 ---------------
253
254 **Import name:** ``jinja2.ext.debug``
255
256 Adds a ``{% debug %}`` tag to dump the current context as well as the
257 available filters and tests. This is useful to see what's available to
258 use in the template without setting up a debugger.
259
260
261 .. _writing-extensions:
262
263 Writing Extensions
264 ------------------
265
266 .. module:: jinja2.ext
267
268 By writing extensions you can add custom tags to Jinja. This is a non-trivial
269 task and usually not needed as the default tags and expressions cover all
270 common use cases. The i18n extension is a good example of why extensions are
271 useful. Another one would be fragment caching.
272
273 When writing extensions you have to keep in mind that you are working with the
274 Jinja template compiler which does not validate the node tree you are passing
275 to it. If the AST is malformed you will get all kinds of compiler or runtime
276 errors that are horrible to debug. Always make sure you are using the nodes
277 you create correctly. The API documentation below shows which nodes exist and
278 how to use them.
279
280
281 Example Extensions
282 ------------------
283
284 Cache
285 ~~~~~
286
287 The following example implements a ``cache`` tag for Jinja by using the
288 `cachelib`_ library:
289
290 .. literalinclude:: examples/cache_extension.py
291 :language: python
292
293 And here is how you use it in an environment::
294
295 from jinja2 import Environment
296 from cachelib import SimpleCache
297
298 env = Environment(extensions=[FragmentCacheExtension])
299 env.fragment_cache = SimpleCache()
300
301 Inside the template it's then possible to mark blocks as cacheable. The
302 following example caches a sidebar for 300 seconds:
303
304 .. sourcecode:: html+jinja
305
306 {% cache 'sidebar', 300 %}
307 <div class="sidebar">
308 ...
309 </div>
310 {% endcache %}
311
312 .. _cachelib: https://github.com/pallets/cachelib
313
314
315 Inline ``gettext``
316 ~~~~~~~~~~~~~~~~~~
317
318 The following example demonstrates using :meth:`Extension.filter_stream`
319 to parse calls to the ``_()`` gettext function inline with static data
320 without needing Jinja blocks.
321
322 .. code-block:: html
323
324 <h1>_(Welcome)</h1>
325 <p>_(This is a paragraph)</p>
326
327 It requires the i18n extension to be loaded and configured.
328
329 .. literalinclude:: examples/inline_gettext_extension.py
330 :language: python
331
332
333 Extension API
334 -------------
335
336 Extension
337 ~~~~~~~~~
338
339 Extensions always have to extend the :class:`jinja2.ext.Extension` class:
340
341 .. autoclass:: Extension
342 :members: preprocess, filter_stream, parse, attr, call_method
343
344 .. attribute:: identifier
345
346 The identifier of the extension. This is always the true import name
347 of the extension class and must not be changed.
348
349 .. attribute:: tags
350
351 If the extension implements custom tags this is a set of tag names
352 the extension is listening for.
353
354
355 Parser
356 ~~~~~~
357
358 The parser passed to :meth:`Extension.parse` provides ways to parse
359 expressions of different types. The following methods may be used by
360 extensions:
361
362 .. autoclass:: jinja2.parser.Parser
363 :members: parse_expression, parse_tuple, parse_assign_target,
364 parse_statements, free_identifier, fail
365
366 .. attribute:: filename
367
368 The filename of the template the parser processes. This is **not**
369 the load name of the template. For the load name see :attr:`name`.
370 For templates that were not loaded form the file system this is
371 ``None``.
372
373 .. attribute:: name
374
375 The load name of the template.
376
377 .. attribute:: stream
378
379 The current :class:`~jinja2.lexer.TokenStream`
380
381 .. autoclass:: jinja2.lexer.TokenStream
382 :members: push, look, eos, skip, __next__, next_if, skip_if, expect
383
384 .. attribute:: current
385
386 The current :class:`~jinja2.lexer.Token`.
387
388 .. autoclass:: jinja2.lexer.Token
389 :members: test, test_any
390
391 .. attribute:: lineno
392
393 The line number of the token
394
395 .. attribute:: type
396
397 The type of the token. This string is interned so you may compare
398 it with arbitrary strings using the ``is`` operator.
399
400 .. attribute:: value
401
402 The value of the token.
403
404 There is also a utility function in the lexer module that can count newline
405 characters in strings:
406
407 .. autofunction:: jinja2.lexer.count_newlines
408
409
410 AST
411 ~~~
412
413 The AST (Abstract Syntax Tree) is used to represent a template after parsing.
414 It's build of nodes that the compiler then converts into executable Python
415 code objects. Extensions that provide custom statements can return nodes to
416 execute custom Python code.
417
418 The list below describes all nodes that are currently available. The AST may
419 change between Jinja versions but will stay backwards compatible.
420
421 For more information have a look at the repr of :meth:`jinja2.Environment.parse`.
422
423 .. module:: jinja2.nodes
424
425 .. jinja:nodes:: jinja2.nodes.Node
426
427 .. autoexception:: Impossible