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 fileTake 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 back1.. _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-----------------13update docs on adding extensions (#1237)sixtyfathomsbefore adoption2f41690
line 14why, one step back14Extensions are added to the Jinja environment at creation time. To add anMerge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
line 15why, one step back15extension pass a list of extension classes or import paths to theMerge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 16why, one step back16``extensions`` parameter of the :class:`~jinja2.Environment` constructor. The followingMerge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 17–18why, one step back17example creates a Jinja environment with the i18n extension loaded::18Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 19why, one step back19 jinja_env = Environment(extensions=['jinja2.ext.i18n'])update docs on adding extensions (#1237)sixtyfathomsbefore adoption2f41690
lines 20–23why, one step back2021To 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 back242526.. _i18n-extension:2728i18n Extension29--------------30Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 31why, one step back31**Import name:** ``jinja2.ext.i18n``Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 32–36why, one step back3233The 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``.36Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228
lines 37–40why, one step back37After 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 back41Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228
line 42why, one step back42Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 43–48why, one step back43Environment Methods44~~~~~~~~~~~~~~~~~~~4546After enabling the extension, the environment provides the following47additional methods:48Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 49why, one step back49.. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 50–51why, one step back5051 Installs a translation globally for the environment. TheMerge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228
lines 52–53why, one step back52 ``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 back54 :class:`gettext.NullTranslations`, :class:`gettext.GNUTranslations`,55 and `Babel`_\s ``Translations`` are supported.56Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228
lines 57–58why, one step back57 .. versionchanged:: 3.058 Added ``pgettext`` and ``npgettext``.Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
line 59why, one step back59Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228
lines 60–62why, one step back60 .. versionchanged:: 2.561 Added new-style gettext support.62Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 63why, one step back63.. method:: jinja2.Environment.install_null_translations(newstyle=False)Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 64–70why, one step back6465 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.70Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228
line 71why, one step back71.. 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 back72Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228
lines 73–76why, one step back73 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`.Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 77–80why, one step back7778 If ``newstyle`` is activated, the callables are wrapped to work like79 newstyle callables. See :ref:`newstyle-gettext` for more information.80Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228
lines 81–82why, one step back81 .. versionchanged:: 3.082 Added ``pgettext`` and ``npgettext``.Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
line 83why, one step back83Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228
lines 84–86why, one step back84 .. versionadded:: 2.585 Added new-style gettext support.86Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 87why, one step back87.. method:: jinja2.Environment.uninstall_gettext_translations()Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 88–90why, one step back8889 Uninstall the environment's globally installed translation.90Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 91why, one step back91.. method:: jinja2.Environment.extract_translations(source)Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 92–101why, one step back9293 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 back102 - ``message`` is the string itself, or a tuple of strings for103 functions with multiple arguments.Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 104–115why, one step back104105 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 back116 env = Environment(extensions=["jinja2.ext.i18n"])Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 117–125why, one step back117 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.htmlMerge branch '3.0.x'David Lordbefore adoptione20a52e
line 126why, one step back126.. _Babel: https://babel.pocoo.org/Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 127–168why, one step back127128129Whitespace 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 back169 {{ 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 back173174New 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 back182 {{ 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 back184185The 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--------------------203Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 204why, one step back204**Import name:** ``jinja2.ext.do``Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 205–214why, one step back205206The "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-------------214Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 215why, one step back215**Import name:** ``jinja2.ext.loopcontrols``Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 216–225why, one step back216217This 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--------------225Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 226why, one step back226**Import name:** ``jinja2.ext.with_``Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 227–236why, one step back227228.. versionchanged:: 2.9229230 This extension is now built-in and no longer does anything.231232.. _autoescape-extension:233234Autoescape Extension235--------------------236Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 237why, one step back237**Import name:** ``jinja2.ext.autoescape``Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 238–249why, one step back238239.. versionchanged:: 2.9240241 This extension was removed and is now built-in. Enabling the242 extension no longer does anything.243244245.. _debug-extension:246247Debug Extension248---------------249Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 250why, one step back250**Import name:** ``jinja2.ext.debug``Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 251–261why, one step back251252Adds 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------------------261Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 262why, one step back262.. module:: jinja2.extMerge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 263–276why, one step back263264By 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.275276Merge pull request #1125 from pallets/styleDavid Lordbefore adoption42d4a4e
lines 277–282why, one step back277Example Extensions278------------------279280Cache281~~~~~282Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 283–285why, one step back283The following example implements a ``cache`` tag for Jinja by using the284`cachelib`_ library:285Merge pull request #1125 from pallets/styleDavid Lordbefore adoption42d4a4e
line 286why, one step back286.. literalinclude:: examples/cache_extension.pyMerge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 287–290why, one step back287 :language: python288289And here is how you use it in an environment::290Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 291why, one step back291 from jinja2 import EnvironmentMerge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 292–309why, one step back292 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/cachelib309Merge pull request #1125 from pallets/styleDavid Lordbefore adoption42d4a4e
lines 310–328why, one step back310311Inline ``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: python327328Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
line 329why, one step back329Extension APIMerge pull request #1125 from pallets/styleDavid Lordbefore adoption42d4a4e
line 330why, one step back330-------------Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
line 331why, one step back331Merge pull request #1125 from pallets/styleDavid Lordbefore adoption42d4a4e
lines 332–334why, one step back332Extension333~~~~~~~~~334Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 335why, one step back335Extensions 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 back336337.. 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.349350Merge pull request #1125 from pallets/styleDavid Lordbefore adoption42d4a4e
lines 351–353why, one step back351Parser352~~~~~~353Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 354–357why, one step back354The parser passed to :meth:`Extension.parse` provides ways to parse355expressions of different types. The following methods may be used by356extensions:357Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 358why, one step back358.. autoclass:: jinja2.parser.ParserMerge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 359–374why, one step back359 :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:: stream374Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 375why, one step back375 The current :class:`~jinja2.lexer.TokenStream`Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
line 376why, one step back376Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 377why, one step back377.. autoclass:: jinja2.lexer.TokenStreamMerge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 378–381why, one step back378 :members: push, look, eos, skip, __next__, next_if, skip_if, expect379380 .. attribute:: current381Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 382why, one step back382 The current :class:`~jinja2.lexer.Token`.Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
line 383why, one step back383Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 384why, one step back384.. autoclass:: jinja2.lexer.TokenMerge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 385–402why, one step back385 :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:402Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 403why, one step back403.. autofunction:: jinja2.lexer.count_newlinesMerge pull request #1125 from pallets/styleDavid Lordbefore adoption42d4a4e
line 404why, one step back404Merge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 405–416why, one step back405406AST407~~~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.416Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 417why, one step back417For 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 back418Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 419why, one step back419.. module:: jinja2.nodesMerge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
line 420why, one step back420Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 421why, one step back421.. jinja:nodes:: jinja2.nodes.NodeMerge pull request #1105 from areebbeigh/issue-1102David Lordbefore adoption5d33f67
lines 422–423why, one step back422423.. autoexception:: Impossible