Skip to content
Myr

extensions.rst

This file

Path

docs/extensions.rst

254 lines · 8.0 KiB

Last changed by

Added example extension that uses the stream filtering and added unittests.Armin Ronacherbefore adoptiond02fc7d

History of this file

Take it

1.. _jinja-extensions:23Extensions4==========56Jinja2 supports extensions that can add extra filters, tests, globals or even7extend the parser.  The main motivation of extensions is it to move often used8code into a reusable class like adding support for internationalization.91011Adding Extensions12-----------------1314Extensions are added to the Jinja2 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`environment` parameter of the :class:`Environment` constructor.  The following18example creates a Jinja2 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`2930Jinja2 currently comes with one extension, the i18n extension.  It can be31used in combination with `gettext`_ or `babel`_.  If the i18n extension is32enabled Jinja2 provides a `trans` statement that marks the wrapped string as33translatable and calls `gettext`.3435After enabling dummy `_` function that forwards calls to `gettext` is added36to the environment globals.  An internationalized application then has to37provide at least an `gettext` and optoinally a `ngettext` function into the38namespace.  Either globally or for each rendering.3940After enabling of the extension the environment provides the following41additional methods:4243.. method:: jinja2.Environment.install_gettext_translations(translations)4445    Installs a translation globally for that environment.  The tranlations46    object provided must implement at least `ugettext` and `ungettext`.47    The `gettext.NullTranslations` and `gettext.GNUTranslations` classes48    as well as `Babel`_\s `Translations` class are supported.4950.. method:: jinja2.Environment.install_null_translations()5152    Install dummy gettext functions.  This is useful if you want to prepare53    the application for internationalization but don't want to implement the54    full internationalization system yet.5556.. method:: jinja2.Environment.uninstall_gettext_translations()5758    Uninstall the translations again.5960.. method:: jinja2.Environment.extract_translations(source)6162    Extract localizable strings from the given template node or source.6364    For every string found this function yields a ``(lineno, function,65    message)`` tuple, where:6667    * `lineno` is the number of the line on which the string was found,68    * `function` is the name of the `gettext` function used (if the69      string was extracted from embedded Python code), and70    *  `message` is the string itself (a `unicode` object, or a tuple71       of `unicode` objects for functions with multiple string arguments).7273    If `Babel`_ is installed :ref:`the babel integration <babel-integration>`74    can be used to extract strings for babel.7576For a web application that is available in multiple languages but gives all77the users the same language (for example a multilingual forum software78installed for a French community) may load the translations once and add the79translation methods to the environment at environment generation time::8081    translations = get_gettext_translations()82    env = Environment(extensions=['jinja2.ext.i18n'])83    env.install_gettext_translations(translations)8485The `get_gettext_translations` function would return the translator for the86current configuration.  (For example by using `gettext.find`)8788The usage of the `i18n` extension for template designers is covered as part89:ref:`of the template documentation <i18n-in-templates>`.9091.. _gettext: http://docs.python.org/dev/library/gettext92.. _Babel: http://babel.edgewall.org/939495Expression Statement96--------------------9798**Import name:** `jinja2.ext.do`99100The "do" aka expression-statement extension adds a simple `do` tag to the101template engine that works like a variable expression but ignores the102return value.103104.. _loopcontrols-extension:105106Loop Controls107-------------108109**Import name:** `jinja2.ext.loopcontrols`110111This extension adds support for `break` and `continue` in loops.  After112enabling Jinja2 provides those two keywords which work exactly like in113Python.114115116.. _writing-extensions:117118Writing Extensions119------------------120121.. module:: jinja2.ext122123By writing extensions you can add custom tags to Jinja2.  This is a non trival124task and usually not needed as the default tags and expressions cover all125common use cases.  The i18n extension is a good example of why extensions are126useful, another one would be fragment caching.127128When writing extensions you have to keep in mind that you are working with the129Jinja2 template compiler which does not validate the node tree you are possing130to it.  If the AST is malformed you will get all kinds of compiler or runtime131errors that are horrible to debug.  Always make sure you are using the nodes132you create correctly.  The API documentation below shows which nodes exist and133how to use them.134135Example Extension136~~~~~~~~~~~~~~~~~137138The following example implements a `cache` tag for Jinja2 by using the139`Werkzeug`_ caching contrib module:140141.. literalinclude:: cache_extension.py142    :language: python143144And here is how you use it in an environment::145146    from jinja2 import Environment147    from werkzeug.contrib.cache import SimpleCache148149    env = Environment(extensions=[FragmentCacheExtension])150    env.fragment_cache = SimpleCache()151152Inside the template it's then possible to mark blocks as cacheable.  The153following example caches a sidebar for 300 seconds:154155.. sourcecode:: html+jinja156157    {% cache 'sidebar', 300 %}158    <div class="sidebar">159        ...160    </div>161    {% endcache %}162163.. _Werkzeug: http://werkzeug.pocoo.org/164165Extension API166~~~~~~~~~~~~~167168Extensions always have to extend the :class:`jinja2.ext.Extension` class:169170.. autoclass:: Extension171    :members: preprocess, filter_stream, parse, attr, call_method172173    .. attribute:: identifier174175        The identifier of the extension.  This is always the true import name176        of the extension class and must not be changed.177178    .. attribute:: tags179180        If the extension implements custom tags this is a set of tag names181        the extension is listening for.182183Parser API184~~~~~~~~~~185186The parser passed to :meth:`Extension.parse` provides ways to parse187expressions of different types.  The following methods may be used by188extensions:189190.. autoclass:: jinja2.parser.Parser191    :members: parse_expression, parse_tuple, parse_assign_target,192              parse_statements, free_identifier, fail193194    .. attribute:: filename195196        The filename of the template the parser processes.  This is **not**197        the load name of the template.  For the load name see :attr:`name`.198        For templates that were not loaded form the file system this is199        `None`.200201    .. attribute:: name202203        The load name of the template.204205    .. attribute:: stream206207        The current :class:`~jinja2.lexer.TokenStream`208209.. autoclass:: jinja2.lexer.TokenStream210   :members: push, look, eos, skip, next, next_if, skip_if, expect211212   .. attribute:: current213214        The current :class:`~jinja2.lexer.Token`.215216.. autoclass:: jinja2.lexer.Token217    :members: test, test_any218219    .. attribute:: lineno220221        The line number of the token222223    .. attribute:: type224225        The type of the token.  This string is interned so you may compare226        it with arbitrary strings using the `is` operator.227228    .. attribute:: value229230        The value of the token.231232There is also a utility function in the lexer module that can count newline233characters in strings:234235.. autofunction:: jinja2.lexer.count_newlines236237AST238~~~239240The AST (Abstract Syntax Tree) is used to represent a template after parsing.241It's build of nodes that the compiler then converts into executable Python242code objects.  Extensions that provide custom statements can return nodes to243execute custom Python code.244245The list below describes all nodes that are currently available.  The AST may246change between Jinja2 versions but will stay backwards compatible.247248For more information have a look at the repr of :meth:`jinja2.Environment.parse`.249250.. module:: jinja2.nodes251252.. jinjanodes::253254.. autoexception:: Impossible