Skip to content
Myr

extensions.rst

This file

Path

docs/extensions.rst

423 lines · 12.5 KiB

Last changed by

Merge branch '3.0.x'David Lordbefore adoptione20a52e

History of this file

Take it

The walk stopped after 200 commits: lines older than 5d33f67 point at it.

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 1–13why, one step back
1.. _jinja-extensions:
23Extensions4==========56Jinja supports extensions that can add extra filters, tests, globals or even7extend the parser. The main motivation of extensions is to move often used8code into a reusable class like adding support for internationalization.91011Adding Extensions12-----------------13

update docs on adding extensions (#1237)sixtyfathomsbefore adoption2f41690

line 14why, one step back
14Extensions are added to the Jinja environment at creation time. To add an

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

line 15why, one step back
15extension pass a list of extension classes or import paths to the

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

line 16why, one step back
16``extensions`` parameter of the :class:`~jinja2.Environment` constructor. The following

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 17–18why, one step back
17example creates a Jinja environment with the i18n extension loaded::
18

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

line 19why, one step back
19 jinja_env = Environment(extensions=['jinja2.ext.i18n'])

update docs on adding extensions (#1237)sixtyfathomsbefore adoption2f41690

lines 20–23why, one step back
20
21To add extensions after creation time, use the :meth:`~jinja2.Environment.add_extension` method::2223 jinja_env.add_extension('jinja2.ext.debug')

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 24–30why, one step back
24
2526.. _i18n-extension:2728i18n Extension29--------------30

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

line 31why, one step back
31**Import name:** ``jinja2.ext.i18n``

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 32–36why, one step back
32
33The i18n extension can be used in combination with `gettext`_ or34`Babel`_. When it's enabled, Jinja provides a ``trans`` statement that35marks a block as translatable and calls ``gettext``.36

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 37–40why, one step back
37After enabling, an application has to provide functions for ``gettext``,
38``ngettext``, and optionally ``pgettext`` and ``npgettext``, either39globally or when rendering. A ``_()`` function is added as an alias to40the ``gettext`` function.

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

line 41why, one step back
41

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

line 42why, one step back
42

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 43–48why, one step back
43Environment Methods
44~~~~~~~~~~~~~~~~~~~4546After enabling the extension, the environment provides the following47additional methods:48

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

line 49why, one step back
49.. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 50–51why, one step back
50
51 Installs a translation globally for the environment. The

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 52–53why, one step back
52 ``translations`` object must implement ``gettext``, ``ngettext``,
53 and optionally ``pgettext`` and ``npgettext``.

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 54–56why, one step back
54 :class:`gettext.NullTranslations`, :class:`gettext.GNUTranslations`,
55 and `Babel`_\s ``Translations`` are supported.56

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 57–58why, one step back
57 .. versionchanged:: 3.0
58 Added ``pgettext`` and ``npgettext``.

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

line 59why, one step back
59

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 60–62why, one step back
60 .. versionchanged:: 2.5
61 Added new-style gettext support.62

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

line 63why, one step back
63.. method:: jinja2.Environment.install_null_translations(newstyle=False)

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 64–70why, one step back
64
65 Install no-op gettext functions. This is useful if you want to66 prepare the application for internationalization but don't want to67 implement the full system yet.6869 .. versionchanged:: 2.5 Added new-style gettext support.70

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

line 71why, one step back
71.. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False, pgettext=None, npgettext=None)

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

line 72why, one step back
72

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 73–76why, one step back
73 Install the given ``gettext``, ``ngettext``, ``pgettext``, and
74 ``npgettext`` callables into the environment. They should behave75 exactly like :func:`gettext.gettext`, :func:`gettext.ngettext`,76 :func:`gettext.pgettext` and :func:`gettext.npgettext`.

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 77–80why, one step back
77
78 If ``newstyle`` is activated, the callables are wrapped to work like79 newstyle callables. See :ref:`newstyle-gettext` for more information.80

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 81–82why, one step back
81 .. versionchanged:: 3.0
82 Added ``pgettext`` and ``npgettext``.

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

line 83why, one step back
83

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 84–86why, one step back
84 .. versionadded:: 2.5
85 Added new-style gettext support.86

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

line 87why, one step back
87.. method:: jinja2.Environment.uninstall_gettext_translations()

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 88–90why, one step back
88
89 Uninstall the environment's globally installed translation.90

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

line 91why, one step back
91.. method:: jinja2.Environment.extract_translations(source)

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 92–101why, one step back
92
93 Extract localizable strings from the given template node or source.9495 For every string found this function yields a ``(lineno, function,96 message)`` tuple, where:9798 - ``lineno`` is the number of the line on which the string was99 found.100 - ``function`` is the name of the ``gettext`` function used (if101 the string was extracted from embedded Python code).

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

lines 102–103why, one step back
102 - ``message`` is the string itself, or a tuple of strings for
103 functions with multiple arguments.

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 104–115why, one step back
104
105 If `Babel`_ is installed, see :ref:`babel-integration` to extract106 the strings.107108For a web application that is available in multiple languages but gives109all the users the same language (for example, multilingual forum110software installed for a French community), the translation may be111installed when the environment is created.112113.. code-block:: python114115 translations = get_gettext_translations()

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

line 116why, one step back
116 env = Environment(extensions=["jinja2.ext.i18n"])

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 117–125why, one step back
117 env.install_gettext_translations(translations)
118119The ``get_gettext_translations`` function would return the translator120for the current configuration, for example by using ``gettext.find``.121122The usage of the ``i18n`` extension for template designers is covered in123:ref:`the template documentation <i18n-in-templates>`.124125.. _gettext: https://docs.python.org/3/library/gettext.html

Merge branch '3.0.x'David Lordbefore adoptione20a52e

line 126why, one step back
126.. _Babel: https://babel.pocoo.org/

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 127–168why, one step back
127
128129Whitespace Trimming130~~~~~~~~~~~~~~~~~~~131132.. versionadded:: 2.10133134Within ``{% trans %}`` blocks, it can be useful to trim line breaks and135whitespace so that the block of text looks like a simple string with136single spaces in the translation file.137138Linebreaks and surrounding whitespace can be automatically trimmed by139enabling the ``ext.i18n.trimmed`` :ref:`policy <ext-i18n-trimmed>`.140141142.. _newstyle-gettext:143144New Style Gettext145~~~~~~~~~~~~~~~~~146147.. versionadded:: 2.5148149New style gettext calls are less to type, less error prone, and support150autoescaping better.151152You can use "new style" gettext calls by setting153``env.newstyle_gettext = True`` or passing ``newstyle=True`` to154``env.install_translations``. They are fully supported by the Babel155extraction tool, but might not work as expected with other extraction156tools.157158With standard ``gettext`` calls, string formatting is a separate step159done with the ``|format`` filter. This requires duplicating work for160``ngettext`` calls.161162.. sourcecode:: jinja163164 {{ gettext("Hello, World!") }}165 {{ gettext("Hello, %(name)s!")|format(name=name) }}166 {{ ngettext(167 "%(num)d apple", "%(num)d apples", apples|count168 )|format(num=apples|count) }}

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 169–172why, one step back
169 {{ pgettext("greeting", "Hello, World!") }}
170 {{ npgettext(171 "fruit", "%(num)d apple", "%(num)d apples", apples|count172 )|format(num=apples|count) }}

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 173–181why, one step back
173
174New style ``gettext`` make formatting part of the call, and behind the175scenes enforce more consistency.176177.. sourcecode:: jinja178179 {{ gettext("Hello, World!") }}180 {{ gettext("Hello, %(name)s!", name=name) }}181 {{ ngettext("%(num)d apple", "%(num)d apples", apples|count) }}

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 182–183why, one step back
182 {{ pgettext("greeting", "Hello, World!") }}
183 {{ npgettext("fruit", "%(num)d apple", "%(num)d apples", apples|count) }}

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 184–203why, one step back
184
185The advantages of newstyle gettext are:186187- There's no separate formatting step, you don't have to remember to188 use the ``|format`` filter.189- Only named placeholders are allowed. This solves a common problem190 translators face because positional placeholders can't switch191 positions meaningfully. Named placeholders always carry semantic192 information about what value goes where.193- String formatting is used even if no placeholders are used, which194 makes all strings use a consistent format. Remember to escape any195 raw percent signs as ``%%``, such as ``100%%``.196- The translated string is marked safe, formatting performs escaping197 as needed. Mark a parameter as ``|safe`` if it has already been198 escaped.199200201Expression Statement202--------------------203

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

line 204why, one step back
204**Import name:** ``jinja2.ext.do``

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 205–214why, one step back
205
206The "do" aka expression-statement extension adds a simple ``do`` tag to the207template engine that works like a variable expression but ignores the208return value.209210.. _loopcontrols-extension:211212Loop Controls213-------------214

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

line 215why, one step back
215**Import name:** ``jinja2.ext.loopcontrols``

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 216–225why, one step back
216
217This extension adds support for ``break`` and ``continue`` in loops. After218enabling, Jinja provides those two keywords which work exactly like in219Python.220221.. _with-extension:222223With Statement224--------------225

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

line 226why, one step back
226**Import name:** ``jinja2.ext.with_``

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 227–236why, one step back
227
228.. versionchanged:: 2.9229230 This extension is now built-in and no longer does anything.231232.. _autoescape-extension:233234Autoescape Extension235--------------------236

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

line 237why, one step back
237**Import name:** ``jinja2.ext.autoescape``

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 238–249why, one step back
238
239.. versionchanged:: 2.9240241 This extension was removed and is now built-in. Enabling the242 extension no longer does anything.243244245.. _debug-extension:246247Debug Extension248---------------249

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

line 250why, one step back
250**Import name:** ``jinja2.ext.debug``

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 251–261why, one step back
251
252Adds a ``{% debug %}`` tag to dump the current context as well as the253available filters and tests. This is useful to see what's available to254use in the template without setting up a debugger.255256257.. _writing-extensions:258259Writing Extensions260------------------261

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

line 262why, one step back
262.. module:: jinja2.ext

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 263–276why, one step back
263
264By writing extensions you can add custom tags to Jinja. This is a non-trivial265task and usually not needed as the default tags and expressions cover all266common use cases. The i18n extension is a good example of why extensions are267useful. Another one would be fragment caching.268269When writing extensions you have to keep in mind that you are working with the270Jinja template compiler which does not validate the node tree you are passing271to it. If the AST is malformed you will get all kinds of compiler or runtime272errors that are horrible to debug. Always make sure you are using the nodes273you create correctly. The API documentation below shows which nodes exist and274how to use them.275276

Merge pull request #1125 from pallets/styleDavid Lordbefore adoption42d4a4e

lines 277–282why, one step back
277Example Extensions
278------------------279280Cache281~~~~~282

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 283–285why, one step back
283The following example implements a ``cache`` tag for Jinja by using the
284`cachelib`_ library:285

Merge pull request #1125 from pallets/styleDavid Lordbefore adoption42d4a4e

line 286why, one step back
286.. literalinclude:: examples/cache_extension.py

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 287–290why, one step back
287 :language: python
288289And here is how you use it in an environment::290

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

line 291why, one step back
291 from jinja2 import Environment

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 292–309why, one step back
292 from cachelib import SimpleCache
293294 env = Environment(extensions=[FragmentCacheExtension])295 env.fragment_cache = SimpleCache()296297Inside the template it's then possible to mark blocks as cacheable. The298following example caches a sidebar for 300 seconds:299300.. sourcecode:: html+jinja301302 {% cache 'sidebar', 300 %}303 <div class="sidebar">304 ...305 </div>306 {% endcache %}307308.. _cachelib: https://github.com/pallets/cachelib309

Merge pull request #1125 from pallets/styleDavid Lordbefore adoption42d4a4e

lines 310–328why, one step back
310
311Inline ``gettext``312~~~~~~~~~~~~~~~~~~313314The following example demonstrates using :meth:`Extension.filter_stream`315to parse calls to the ``_()`` gettext function inline with static data316without needing Jinja blocks.317318.. code-block:: html319320 <h1>_(Welcome)</h1>321 <p>_(This is a paragraph)</p>322323It requires the i18n extension to be loaded and configured.324325.. literalinclude:: examples/inline_gettext_extension.py326 :language: python327328

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

line 329why, one step back
329Extension API

Merge pull request #1125 from pallets/styleDavid Lordbefore adoption42d4a4e

line 330why, one step back
330-------------

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

line 331why, one step back
331

Merge pull request #1125 from pallets/styleDavid Lordbefore adoption42d4a4e

lines 332–334why, one step back
332Extension
333~~~~~~~~~334

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

line 335why, one step back
335Extensions always have to extend the :class:`jinja2.ext.Extension` class:

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 336–350why, one step back
336
337.. autoclass:: Extension338 :members: preprocess, filter_stream, parse, attr, call_method339340 .. attribute:: identifier341342 The identifier of the extension. This is always the true import name343 of the extension class and must not be changed.344345 .. attribute:: tags346347 If the extension implements custom tags this is a set of tag names348 the extension is listening for.349350

Merge pull request #1125 from pallets/styleDavid Lordbefore adoption42d4a4e

lines 351–353why, one step back
351Parser
352~~~~~~353

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 354–357why, one step back
354The parser passed to :meth:`Extension.parse` provides ways to parse
355expressions of different types. The following methods may be used by356extensions:357

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

line 358why, one step back
358.. autoclass:: jinja2.parser.Parser

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 359–374why, one step back
359 :members: parse_expression, parse_tuple, parse_assign_target,
360 parse_statements, free_identifier, fail361362 .. attribute:: filename363364 The filename of the template the parser processes. This is **not**365 the load name of the template. For the load name see :attr:`name`.366 For templates that were not loaded form the file system this is367 ``None``.368369 .. attribute:: name370371 The load name of the template.372373 .. attribute:: stream374

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

line 375why, one step back
375 The current :class:`~jinja2.lexer.TokenStream`

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

line 376why, one step back
376

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

line 377why, one step back
377.. autoclass:: jinja2.lexer.TokenStream

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 378–381why, one step back
378 :members: push, look, eos, skip, __next__, next_if, skip_if, expect
379380 .. attribute:: current381

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

line 382why, one step back
382 The current :class:`~jinja2.lexer.Token`.

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

line 383why, one step back
383

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

line 384why, one step back
384.. autoclass:: jinja2.lexer.Token

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 385–402why, one step back
385 :members: test, test_any
386387 .. attribute:: lineno388389 The line number of the token390391 .. attribute:: type392393 The type of the token. This string is interned so you may compare394 it with arbitrary strings using the ``is`` operator.395396 .. attribute:: value397398 The value of the token.399400There is also a utility function in the lexer module that can count newline401characters in strings:402

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

line 403why, one step back
403.. autofunction:: jinja2.lexer.count_newlines

Merge pull request #1125 from pallets/styleDavid Lordbefore adoption42d4a4e

line 404why, one step back
404

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 405–416why, one step back
405
406AST407~~~408409The AST (Abstract Syntax Tree) is used to represent a template after parsing.410It's build of nodes that the compiler then converts into executable Python411code objects. Extensions that provide custom statements can return nodes to412execute custom Python code.413414The list below describes all nodes that are currently available. The AST may415change between Jinja versions but will stay backwards compatible.416

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

line 417why, one step back
417For more information have a look at the repr of :meth:`jinja2.Environment.parse`.

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

line 418why, one step back
418

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

line 419why, one step back
419.. module:: jinja2.nodes

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

line 420why, one step back
420

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

line 421why, one step back
421.. jinja:nodes:: jinja2.nodes.Node

Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67

lines 422–423why, one step back
422
423.. autoexception:: Impossible