Skip to content
Myr

extensions.rst

This file

Path

docs/extensions.rst

404 lines · 11.9 KiB

Last changed by

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

History of this file

Take it

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-----------------1314Extensions are added to the Jinja environment at creation time.  Once the15environment is created additional extensions cannot be added.  To add an16extension pass a list of extension classes or import paths to the17``extensions`` parameter of the :class:`~jinja2.Environment` constructor.  The following18example creates a Jinja environment with the i18n extension loaded::1920    jinja_env = Environment(extensions=['jinja2.ext.i18n'])212223.. _i18n-extension:2425i18n Extension26--------------2728**Import name:** ``jinja2.ext.i18n``2930The i18n extension can be used in combination with `gettext`_ or31`Babel`_.  When it's enabled, Jinja provides a ``trans`` statement that32marks a block as translatable and calls ``gettext``.3334After enabling, an application has to provide ``gettext`` and35``ngettext`` functions, either globally or when rendering. A ``_()``36function is added as an alias to the ``gettext`` function.3738Environment Methods39~~~~~~~~~~~~~~~~~~~4041After enabling the extension, the environment provides the following42additional methods:4344.. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)4546    Installs a translation globally for the environment. The47    ``translations`` object must implement ``gettext`` and ``ngettext``48    (or ``ugettext`` and ``ungettext`` for Python 2).49    :class:`gettext.NullTranslations`, :class:`gettext.GNUTranslations`,50    and `Babel`_\s ``Translations`` are supported.5152    .. versionchanged:: 2.5 Added new-style gettext support.5354.. method:: jinja2.Environment.install_null_translations(newstyle=False)5556    Install no-op gettext functions. This is useful if you want to57    prepare the application for internationalization but don't want to58    implement the full system yet.5960    .. versionchanged:: 2.5 Added new-style gettext support.6162.. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False)6364    Install the given ``gettext`` and ``ngettext`` callables into the65    environment. They should behave exactly like66    :func:`gettext.gettext` and :func:`gettext.ngettext` (or67    ``ugettext`` and ``ungettext`` for Python 2).6869    If ``newstyle`` is activated, the callables are wrapped to work like70    newstyle callables.  See :ref:`newstyle-gettext` for more information.7172    .. versionadded:: 2.5 Added new-style gettext support.7374.. method:: jinja2.Environment.uninstall_gettext_translations()7576    Uninstall the environment's globally installed translation.7778.. method:: jinja2.Environment.extract_translations(source)7980    Extract localizable strings from the given template node or source.8182    For every string found this function yields a ``(lineno, function,83    message)`` tuple, where:8485    -   ``lineno`` is the number of the line on which the string was86        found.87    -   ``function`` is the name of the ``gettext`` function used (if88        the string was extracted from embedded Python code).89    -   ``message`` is the string itself (``unicode`` on Python 2), or a90        tuple of strings for functions with multiple arguments.9192    If `Babel`_ is installed, see :ref:`babel-integration` to extract93    the strings.9495For a web application that is available in multiple languages but gives96all the users the same language (for example, multilingual forum97software installed for a French community), the translation may be98installed when the environment is created.99100.. code-block:: python101102    translations = get_gettext_translations()103    env = Environment(extensions=["jinja2.ext.i18n"])104    env.install_gettext_translations(translations)105106The ``get_gettext_translations`` function would return the translator107for the current configuration, for example by using ``gettext.find``.108109The usage of the ``i18n`` extension for template designers is covered in110:ref:`the template documentation <i18n-in-templates>`.111112.. _gettext: https://docs.python.org/3/library/gettext.html113.. _Babel: http://babel.pocoo.org/114115116Whitespace Trimming117~~~~~~~~~~~~~~~~~~~118119.. versionadded:: 2.10120121Within ``{% trans %}`` blocks, it can be useful to trim line breaks and122whitespace so that the block of text looks like a simple string with123single spaces in the translation file.124125Linebreaks and surrounding whitespace can be automatically trimmed by126enabling the ``ext.i18n.trimmed`` :ref:`policy <ext-i18n-trimmed>`.127128129.. _newstyle-gettext:130131New Style Gettext132~~~~~~~~~~~~~~~~~133134.. versionadded:: 2.5135136New style gettext calls are less to type, less error prone, and support137autoescaping better.138139You can use "new style" gettext calls by setting140``env.newstyle_gettext = True`` or passing ``newstyle=True`` to141``env.install_translations``. They are fully supported by the Babel142extraction tool, but might not work as expected with other extraction143tools.144145With standard ``gettext`` calls, string formatting is a separate step146done with the ``|format`` filter. This requires duplicating work for147``ngettext`` calls.148149.. sourcecode:: jinja150151    {{ gettext("Hello, World!") }}152    {{ gettext("Hello, %(name)s!")|format(name=name) }}153    {{ ngettext(154           "%(num)d apple", "%(num)d apples", apples|count155       )|format(num=apples|count) }}156157New style ``gettext`` make formatting part of the call, and behind the158scenes enforce more consistency.159160.. sourcecode:: jinja161162    {{ gettext("Hello, World!") }}163    {{ gettext("Hello, %(name)s!", name=name) }}164    {{ ngettext("%(num)d apple", "%(num)d apples", apples|count) }}165166The advantages of newstyle gettext are:167168-   There's no separate formatting step, you don't have to remember to169    use the ``|format`` filter.170-   Only named placeholders are allowed. This solves a common problem171    translators face because positional placeholders can't switch172    positions meaningfully. Named placeholders always carry semantic173    information about what value goes where.174-   String formatting is used even if no placeholders are used, which175    makes all strings use a consistent format. Remember to escape any176    raw percent signs as ``%%``, such as ``100%%``.177-   The translated string is marked safe, formatting performs escaping178    as needed. Mark a parameter as ``|safe`` if it has already been179    escaped.180181182Expression Statement183--------------------184185**Import name:** ``jinja2.ext.do``186187The "do" aka expression-statement extension adds a simple ``do`` tag to the188template engine that works like a variable expression but ignores the189return value.190191.. _loopcontrols-extension:192193Loop Controls194-------------195196**Import name:** ``jinja2.ext.loopcontrols``197198This extension adds support for ``break`` and ``continue`` in loops.  After199enabling, Jinja provides those two keywords which work exactly like in200Python.201202.. _with-extension:203204With Statement205--------------206207**Import name:** ``jinja2.ext.with_``208209.. versionchanged:: 2.9210211    This extension is now built-in and no longer does anything.212213.. _autoescape-extension:214215Autoescape Extension216--------------------217218**Import name:** ``jinja2.ext.autoescape``219220.. versionchanged:: 2.9221222    This extension was removed and is now built-in. Enabling the223    extension no longer does anything.224225226.. _debug-extension:227228Debug Extension229---------------230231**Import name:** ``jinja2.ext.debug``232233Adds a ``{% debug %}`` tag to dump the current context as well as the234available filters and tests. This is useful to see what's available to235use in the template without setting up a debugger.236237238.. _writing-extensions:239240Writing Extensions241------------------242243.. module:: jinja2.ext244245By writing extensions you can add custom tags to Jinja.  This is a non-trivial246task and usually not needed as the default tags and expressions cover all247common use cases.  The i18n extension is a good example of why extensions are248useful. Another one would be fragment caching.249250When writing extensions you have to keep in mind that you are working with the251Jinja template compiler which does not validate the node tree you are passing252to it.  If the AST is malformed you will get all kinds of compiler or runtime253errors that are horrible to debug.  Always make sure you are using the nodes254you create correctly.  The API documentation below shows which nodes exist and255how to use them.256257258Example Extensions259------------------260261Cache262~~~~~263264The following example implements a ``cache`` tag for Jinja by using the265`cachelib`_ library:266267.. literalinclude:: examples/cache_extension.py268    :language: python269270And here is how you use it in an environment::271272    from jinja2 import Environment273    from cachelib import SimpleCache274275    env = Environment(extensions=[FragmentCacheExtension])276    env.fragment_cache = SimpleCache()277278Inside the template it's then possible to mark blocks as cacheable.  The279following example caches a sidebar for 300 seconds:280281.. sourcecode:: html+jinja282283    {% cache 'sidebar', 300 %}284    <div class="sidebar">285        ...286    </div>287    {% endcache %}288289.. _cachelib: https://github.com/pallets/cachelib290291292Inline ``gettext``293~~~~~~~~~~~~~~~~~~294295The following example demonstrates using :meth:`Extension.filter_stream`296to parse calls to the ``_()`` gettext function inline with static data297without needing Jinja blocks.298299.. code-block:: html300301        <h1>_(Welcome)</h1>302        <p>_(This is a paragraph)</p>303304It requires the i18n extension to be loaded and configured.305306.. literalinclude:: examples/inline_gettext_extension.py307    :language: python308309310Extension API311-------------312313Extension314~~~~~~~~~315316Extensions always have to extend the :class:`jinja2.ext.Extension` class:317318.. autoclass:: Extension319    :members: preprocess, filter_stream, parse, attr, call_method320321    .. attribute:: identifier322323        The identifier of the extension.  This is always the true import name324        of the extension class and must not be changed.325326    .. attribute:: tags327328        If the extension implements custom tags this is a set of tag names329        the extension is listening for.330331332Parser333~~~~~~334335The parser passed to :meth:`Extension.parse` provides ways to parse336expressions of different types.  The following methods may be used by337extensions:338339.. autoclass:: jinja2.parser.Parser340    :members: parse_expression, parse_tuple, parse_assign_target,341              parse_statements, free_identifier, fail342343    .. attribute:: filename344345        The filename of the template the parser processes.  This is **not**346        the load name of the template.  For the load name see :attr:`name`.347        For templates that were not loaded form the file system this is348        ``None``.349350    .. attribute:: name351352        The load name of the template.353354    .. attribute:: stream355356        The current :class:`~jinja2.lexer.TokenStream`357358.. autoclass:: jinja2.lexer.TokenStream359   :members: push, look, eos, skip, __next__, next_if, skip_if, expect360361   .. attribute:: current362363        The current :class:`~jinja2.lexer.Token`.364365.. autoclass:: jinja2.lexer.Token366    :members: test, test_any367368    .. attribute:: lineno369370        The line number of the token371372    .. attribute:: type373374        The type of the token.  This string is interned so you may compare375        it with arbitrary strings using the ``is`` operator.376377    .. attribute:: value378379        The value of the token.380381There is also a utility function in the lexer module that can count newline382characters in strings:383384.. autofunction:: jinja2.lexer.count_newlines385386387AST388~~~389390The AST (Abstract Syntax Tree) is used to represent a template after parsing.391It's build of nodes that the compiler then converts into executable Python392code objects.  Extensions that provide custom statements can return nodes to393execute custom Python code.394395The list below describes all nodes that are currently available.  The AST may396change between Jinja versions but will stay backwards compatible.397398For more information have a look at the repr of :meth:`jinja2.Environment.parse`.399400.. module:: jinja2.nodes401402.. jinja:nodes:: jinja2.nodes.Node403404.. autoexception:: Impossible