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

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.414243Environment Methods44~~~~~~~~~~~~~~~~~~~4546After enabling the extension, the environment provides the following47additional methods:4849.. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)5051    Installs a translation globally for the environment. The52    ``translations`` object must implement ``gettext``, ``ngettext``,53    and optionally ``pgettext`` and ``npgettext``.54    :class:`gettext.NullTranslations`, :class:`gettext.GNUTranslations`,55    and `Babel`_\s ``Translations`` are supported.5657    .. versionchanged:: 3.058        Added ``pgettext`` and ``npgettext``.5960    .. versionchanged:: 2.561        Added new-style gettext support.6263.. method:: jinja2.Environment.install_null_translations(newstyle=False)6465    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.7071.. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False, pgettext=None, npgettext=None)7273    Install the given ``gettext``, ``ngettext``, ``pgettext``, and74    ``npgettext`` callables into the environment. They should behave75    exactly like :func:`gettext.gettext`, :func:`gettext.ngettext`,76    :func:`gettext.pgettext` and :func:`gettext.npgettext`.7778    If ``newstyle`` is activated, the callables are wrapped to work like79    newstyle callables.  See :ref:`newstyle-gettext` for more information.8081    .. versionchanged:: 3.082        Added ``pgettext`` and ``npgettext``.8384    .. versionadded:: 2.585        Added new-style gettext support.8687.. method:: jinja2.Environment.uninstall_gettext_translations()8889    Uninstall the environment's globally installed translation.9091.. method:: jinja2.Environment.extract_translations(source)9293    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).102    -   ``message`` is the string itself, or a tuple of strings for103        functions with multiple arguments.104105    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()116    env = Environment(extensions=["jinja2.ext.i18n"])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.html126.. _Babel: https://babel.pocoo.org/127128129Whitespace 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) }}169    {{ pgettext("greeting", "Hello, World!") }}170    {{ npgettext(171           "fruit", "%(num)d apple", "%(num)d apples", apples|count172       )|format(num=apples|count) }}173174New 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) }}182    {{ pgettext("greeting", "Hello, World!") }}183    {{ npgettext("fruit", "%(num)d apple", "%(num)d apples", apples|count) }}184185The 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--------------------203204**Import name:** ``jinja2.ext.do``205206The "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-------------214215**Import name:** ``jinja2.ext.loopcontrols``216217This 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--------------225226**Import name:** ``jinja2.ext.with_``227228.. versionchanged:: 2.9229230    This extension is now built-in and no longer does anything.231232.. _autoescape-extension:233234Autoescape Extension235--------------------236237**Import name:** ``jinja2.ext.autoescape``238239.. versionchanged:: 2.9240241    This extension was removed and is now built-in. Enabling the242    extension no longer does anything.243244245.. _debug-extension:246247Debug Extension248---------------249250**Import name:** ``jinja2.ext.debug``251252Adds 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------------------261262.. module:: jinja2.ext263264By 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.275276277Example Extensions278------------------279280Cache281~~~~~282283The following example implements a ``cache`` tag for Jinja by using the284`cachelib`_ library:285286.. literalinclude:: examples/cache_extension.py287    :language: python288289And here is how you use it in an environment::290291    from jinja2 import Environment292    from cachelib import SimpleCache293294    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/cachelib309310311Inline ``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: python327328329Extension API330-------------331332Extension333~~~~~~~~~334335Extensions always have to extend the :class:`jinja2.ext.Extension` class:336337.. 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.349350351Parser352~~~~~~353354The parser passed to :meth:`Extension.parse` provides ways to parse355expressions of different types.  The following methods may be used by356extensions:357358.. autoclass:: jinja2.parser.Parser359    :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:: stream374375        The current :class:`~jinja2.lexer.TokenStream`376377.. autoclass:: jinja2.lexer.TokenStream378   :members: push, look, eos, skip, __next__, next_if, skip_if, expect379380   .. attribute:: current381382        The current :class:`~jinja2.lexer.Token`.383384.. autoclass:: jinja2.lexer.Token385    :members: test, test_any386387    .. 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:402403.. autofunction:: jinja2.lexer.count_newlines404405406AST407~~~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.416417For more information have a look at the repr of :meth:`jinja2.Environment.parse`.418419.. module:: jinja2.nodes420421.. jinja:nodes:: jinja2.nodes.Node422423.. autoexception:: Impossible