Skip to content
Myr

extensions.rst

This file

Path

docs/extensions.rst

427 lines · 12.8 KiB

Last changed by

Merge branch 'stable'David Lordbefore adoptionee6c734

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.  To add an15extension pass a list of extension classes or import paths to the16``extensions`` parameter of the :class:`~jinja2.Environment` constructor.  The following17example creates a Jinja environment with the i18n extension loaded::1819    jinja_env = Environment(extensions=['jinja2.ext.i18n'])2021To add extensions after creation time, use the :meth:`~jinja2.Environment.add_extension` method::2223    jinja_env.add_extension('jinja2.ext.debug')242526.. _i18n-extension:2728i18n Extension29--------------3031**Import name:** ``jinja2.ext.i18n``3233The 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``.3637After 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.4142A convenient way to provide these functions is to call one of the below43methods depending on the translation system in use. If you do not require44actual translation, use ``Environment.install_null_translations`` to45install no-op functions.4647Environment Methods48~~~~~~~~~~~~~~~~~~~4950After enabling the extension, the environment provides the following51additional methods:5253.. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)5455    Installs a translation globally for the environment. The56    ``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.6061    .. versionchanged:: 3.062        Added ``pgettext`` and ``npgettext``.6364    .. versionchanged:: 2.565        Added new-style gettext support.6667.. method:: jinja2.Environment.install_null_translations(newstyle=False)6869    Install no-op gettext functions. This is useful if you want to70    prepare the application for internationalization but don't want to71    implement the full system yet.7273    .. versionchanged:: 2.5 Added new-style gettext support.7475.. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False, pgettext=None, npgettext=None)7677    Install the given ``gettext``, ``ngettext``, ``pgettext``, and78    ``npgettext`` callables into the environment. They should behave79    exactly like :func:`gettext.gettext`, :func:`gettext.ngettext`,80    :func:`gettext.pgettext` and :func:`gettext.npgettext`.8182    If ``newstyle`` is activated, the callables are wrapped to work like83    newstyle callables.  See :ref:`newstyle-gettext` for more information.8485    .. versionchanged:: 3.086        Added ``pgettext`` and ``npgettext``.8788    .. versionadded:: 2.589        Added new-style gettext support.9091.. method:: jinja2.Environment.uninstall_gettext_translations()9293    Uninstall the environment's globally installed translation.9495.. method:: jinja2.Environment.extract_translations(source)9697    Extract localizable strings from the given template node or source.9899    For every string found this function yields a ``(lineno, function,100    message)`` tuple, where:101102    -   ``lineno`` is the number of the line on which the string was103        found.104    -   ``function`` is the name of the ``gettext`` function used (if105        the string was extracted from embedded Python code).106    -   ``message`` is the string itself, or a tuple of strings for107        functions with multiple arguments.108109    If `Babel`_ is installed, see :ref:`babel-integration` to extract110    the strings.111112For a web application that is available in multiple languages but gives113all the users the same language (for example, multilingual forum114software installed for a French community), the translation may be115installed when the environment is created.116117.. code-block:: python118119    translations = get_gettext_translations()120    env = Environment(extensions=["jinja2.ext.i18n"])121    env.install_gettext_translations(translations)122123The ``get_gettext_translations`` function would return the translator124for the current configuration, for example by using ``gettext.find``.125126The usage of the ``i18n`` extension for template designers is covered in127:ref:`the template documentation <i18n-in-templates>`.128129.. _gettext: https://docs.python.org/3/library/gettext.html130.. _Babel: https://babel.pocoo.org/131132133Whitespace Trimming134~~~~~~~~~~~~~~~~~~~135136.. versionadded:: 2.10137138Within ``{% trans %}`` blocks, it can be useful to trim line breaks and139whitespace so that the block of text looks like a simple string with140single spaces in the translation file.141142Linebreaks and surrounding whitespace can be automatically trimmed by143enabling the ``ext.i18n.trimmed`` :ref:`policy <ext-i18n-trimmed>`.144145146.. _newstyle-gettext:147148New Style Gettext149~~~~~~~~~~~~~~~~~150151.. versionadded:: 2.5152153New style gettext calls are less to type, less error prone, and support154autoescaping better.155156You can use "new style" gettext calls by setting157``env.newstyle_gettext = True`` or passing ``newstyle=True`` to158``env.install_translations``. They are fully supported by the Babel159extraction tool, but might not work as expected with other extraction160tools.161162With standard ``gettext`` calls, string formatting is a separate step163done with the ``|format`` filter. This requires duplicating work for164``ngettext`` calls.165166.. sourcecode:: jinja167168    {{ gettext("Hello, World!") }}169    {{ gettext("Hello, %(name)s!")|format(name=name) }}170    {{ ngettext(171           "%(num)d apple", "%(num)d apples", apples|count172       )|format(num=apples|count) }}173    {{ pgettext("greeting", "Hello, World!") }}174    {{ npgettext(175           "fruit", "%(num)d apple", "%(num)d apples", apples|count176       )|format(num=apples|count) }}177178New style ``gettext`` make formatting part of the call, and behind the179scenes enforce more consistency.180181.. sourcecode:: jinja182183    {{ 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) }}188189The advantages of newstyle gettext are:190191-   There's no separate formatting step, you don't have to remember to192    use the ``|format`` filter.193-   Only named placeholders are allowed. This solves a common problem194    translators face because positional placeholders can't switch195    positions meaningfully. Named placeholders always carry semantic196    information about what value goes where.197-   String formatting is used even if no placeholders are used, which198    makes all strings use a consistent format. Remember to escape any199    raw percent signs as ``%%``, such as ``100%%``.200-   The translated string is marked safe, formatting performs escaping201    as needed. Mark a parameter as ``|safe`` if it has already been202    escaped.203204205Expression Statement206--------------------207208**Import name:** ``jinja2.ext.do``209210The "do" aka expression-statement extension adds a simple ``do`` tag to the211template engine that works like a variable expression but ignores the212return value.213214.. _loopcontrols-extension:215216Loop Controls217-------------218219**Import name:** ``jinja2.ext.loopcontrols``220221This extension adds support for ``break`` and ``continue`` in loops.  After222enabling, Jinja provides those two keywords which work exactly like in223Python.224225.. _with-extension:226227With Statement228--------------229230**Import name:** ``jinja2.ext.with_``231232.. versionchanged:: 2.9233234    This extension is now built-in and no longer does anything.235236.. _autoescape-extension:237238Autoescape Extension239--------------------240241**Import name:** ``jinja2.ext.autoescape``242243.. versionchanged:: 2.9244245    This extension was removed and is now built-in. Enabling the246    extension no longer does anything.247248249.. _debug-extension:250251Debug Extension252---------------253254**Import name:** ``jinja2.ext.debug``255256Adds a ``{% debug %}`` tag to dump the current context as well as the257available filters and tests. This is useful to see what's available to258use in the template without setting up a debugger.259260261.. _writing-extensions:262263Writing Extensions264------------------265266.. module:: jinja2.ext267268By writing extensions you can add custom tags to Jinja.  This is a non-trivial269task and usually not needed as the default tags and expressions cover all270common use cases.  The i18n extension is a good example of why extensions are271useful. Another one would be fragment caching.272273When writing extensions you have to keep in mind that you are working with the274Jinja template compiler which does not validate the node tree you are passing275to it.  If the AST is malformed you will get all kinds of compiler or runtime276errors that are horrible to debug.  Always make sure you are using the nodes277you create correctly.  The API documentation below shows which nodes exist and278how to use them.279280281Example Extensions282------------------283284Cache285~~~~~286287The following example implements a ``cache`` tag for Jinja by using the288`cachelib`_ library:289290.. literalinclude:: examples/cache_extension.py291    :language: python292293And here is how you use it in an environment::294295    from jinja2 import Environment296    from cachelib import SimpleCache297298    env = Environment(extensions=[FragmentCacheExtension])299    env.fragment_cache = SimpleCache()300301Inside the template it's then possible to mark blocks as cacheable.  The302following example caches a sidebar for 300 seconds:303304.. sourcecode:: html+jinja305306    {% cache 'sidebar', 300 %}307    <div class="sidebar">308        ...309    </div>310    {% endcache %}311312.. _cachelib: https://github.com/pallets/cachelib313314315Inline ``gettext``316~~~~~~~~~~~~~~~~~~317318The following example demonstrates using :meth:`Extension.filter_stream`319to parse calls to the ``_()`` gettext function inline with static data320without needing Jinja blocks.321322.. code-block:: html323324        <h1>_(Welcome)</h1>325        <p>_(This is a paragraph)</p>326327It requires the i18n extension to be loaded and configured.328329.. literalinclude:: examples/inline_gettext_extension.py330    :language: python331332333Extension API334-------------335336Extension337~~~~~~~~~338339Extensions always have to extend the :class:`jinja2.ext.Extension` class:340341.. autoclass:: Extension342    :members: preprocess, filter_stream, parse, attr, call_method343344    .. attribute:: identifier345346        The identifier of the extension.  This is always the true import name347        of the extension class and must not be changed.348349    .. attribute:: tags350351        If the extension implements custom tags this is a set of tag names352        the extension is listening for.353354355Parser356~~~~~~357358The parser passed to :meth:`Extension.parse` provides ways to parse359expressions of different types.  The following methods may be used by360extensions:361362.. autoclass:: jinja2.parser.Parser363    :members: parse_expression, parse_tuple, parse_assign_target,364              parse_statements, free_identifier, fail365366    .. attribute:: filename367368        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 is371        ``None``.372373    .. attribute:: name374375        The load name of the template.376377    .. attribute:: stream378379        The current :class:`~jinja2.lexer.TokenStream`380381.. autoclass:: jinja2.lexer.TokenStream382   :members: push, look, eos, skip, __next__, next_if, skip_if, expect383384   .. attribute:: current385386        The current :class:`~jinja2.lexer.Token`.387388.. autoclass:: jinja2.lexer.Token389    :members: test, test_any390391    .. attribute:: lineno392393        The line number of the token394395    .. attribute:: type396397        The type of the token.  This string is interned so you may compare398        it with arbitrary strings using the ``is`` operator.399400    .. attribute:: value401402        The value of the token.403404There is also a utility function in the lexer module that can count newline405characters in strings:406407.. autofunction:: jinja2.lexer.count_newlines408409410AST411~~~412413The AST (Abstract Syntax Tree) is used to represent a template after parsing.414It's build of nodes that the compiler then converts into executable Python415code objects.  Extensions that provide custom statements can return nodes to416execute custom Python code.417418The list below describes all nodes that are currently available.  The AST may419change between Jinja versions but will stay backwards compatible.420421For more information have a look at the repr of :meth:`jinja2.Environment.parse`.422423.. module:: jinja2.nodes424425.. jinja:nodes:: jinja2.nodes.Node426427.. autoexception:: Impossible