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 fileTake it
some documentation updatesArmin Ronacherbefore adoptioned98cac
lines 1–19why, one step back1.. _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::19added a function to parse assign targes and documented it for the extension interfaceArmin Ronacherbefore adoption09c002e
line 20why, one step back20 jinja_env = Environment(extensions=['jinja2.ext.i18n'])some documentation updatesArmin Ronacherbefore adoptioned98cac
lines 21–24why, one step back212223.. _i18n-extension:24First extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9
lines 25–26why, one step back25i18n Extension26--------------some documentation updatesArmin Ronacherbefore adoptioned98cac
line 27why, one step back27void -> doArmin Ronacherbefore adoption5d2733f
lines 28–29why, one step back28**Import name:** `jinja2.ext.i18n`29First extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9
lines 30–33why, one step back30Jinja2 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`.some documentation updatesArmin Ronacherbefore adoptioned98cac
line 34why, one step back34more updates on the extension APIArmin Ronacherbefore adoption762079c
lines 35–38why, one step back35After 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.some documentation updatesArmin Ronacherbefore adoptioned98cac
line 39why, one step back39more updates on the extension APIArmin Ronacherbefore adoption762079c
lines 40–75why, one step back40After 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.75some documentation updatesArmin Ronacherbefore adoptioned98cac
lines 76–81why, one step back76For 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()some small documentation fixesArmin Ronacherbefore adoption2b22874
line 82why, one step back82 env = Environment(extensions=['jinja2.ext.i18n'])more updates on the extension APIArmin Ronacherbefore adoption762079c
line 83why, one step back83 env.install_gettext_translations(translations)some documentation updatesArmin Ronacherbefore adoptioned98cac
lines 84–85why, one step back8485The `get_gettext_translations` function would return the translator for themore updates on the extension APIArmin Ronacherbefore adoption762079c
line 86why, one step back86current configuration. (For example by using `gettext.find`)some documentation updatesArmin Ronacherbefore adoptioned98cac
lines 87–91why, one step back8788The 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/gettextmore updates on the extension APIArmin Ronacherbefore adoption762079c
line 92why, one step back92.. _Babel: http://babel.edgewall.org/void -> doArmin Ronacherbefore adoption5d2733f
lines 93–94why, one step back9394more unittests and updated documentation for extensions. Fixed bug in optimizer that caused blocks to be optimized away under some circumstances.Armin Ronacherbefore adoption6df604e
lines 95–96why, one step back95Expression Statement96--------------------void -> doArmin Ronacherbefore adoption5d2733f
lines 97–99why, one step back9798**Import name:** `jinja2.ext.do`99more unittests and updated documentation for extensions. Fixed bug in optimizer that caused blocks to be optimized away under some circumstances.Armin Ronacherbefore adoption6df604e
line 100why, one step back100The "do" aka expression-statement extension adds a simple `do` tag to thevoid -> doArmin Ronacherbefore adoption5d2733f
lines 101–102why, one step back101template engine that works like a variable expression but ignores the102return value.some documentation updatesArmin Ronacherbefore adoptioned98cac
line 103why, one step back103added loopcontrols extension and added unittests for itArmin Ronacherbefore adoption3da9031
lines 104–105why, one step back104.. _loopcontrols-extension:105more unittests and updated documentation for extensions. Fixed bug in optimizer that caused blocks to be optimized away under some circumstances.Armin Ronacherbefore adoption6df604e
lines 106–107why, one step back106Loop Controls107-------------added loopcontrols extension and added unittests for itArmin Ronacherbefore adoption3da9031
lines 108–114why, one step back108109**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.114First extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9
line 115why, one step back115some documentation updatesArmin Ronacherbefore adoptioned98cac
lines 116–120why, one step back116.. _writing-extensions:117118Writing Extensions119------------------120more updates on the extension APIArmin Ronacherbefore adoption762079c
lines 121–122why, one step back121.. module:: jinja2.ext122First extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9
lines 123–127why, one step back123By 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.127added support for dotted names in tests and filtersArmin Ronacherbefore adoptionb9e7875
lines 128–134why, one step back128When 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.134First extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9
lines 135–137why, one step back135Example Extension136~~~~~~~~~~~~~~~~~137more updates on the extension APIArmin Ronacherbefore adoption762079c
lines 138–139why, one step back138The following example implements a `cache` tag for Jinja2 by using the139`Werkzeug`_ caching contrib module:First extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9
lines 140–143why, one step back140141.. literalinclude:: cache_extension.py142 :language: python143more updates on the extension APIArmin Ronacherbefore adoption762079c
line 144why, one step back144And here is how you use it in an environment::First extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9
lines 145–148why, one step back145146 from jinja2 import Environment147 from werkzeug.contrib.cache import SimpleCache148more updates on the extension APIArmin Ronacherbefore adoption762079c
lines 149–150why, one step back149 env = Environment(extensions=[FragmentCacheExtension])150 env.fragment_cache = SimpleCache()more unittests and updated documentation for extensions. Fixed bug in optimizer that caused blocks to be optimized away under some circumstances.Armin Ronacherbefore adoption6df604e
lines 151–161why, one step back151152Inside 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 %}First extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9
lines 162–170why, one step back162163.. _Werkzeug: http://werkzeug.pocoo.org/164165Extension API166~~~~~~~~~~~~~167168Extensions always have to extend the :class:`jinja2.ext.Extension` class:169170.. autoclass:: Extensionadded support for token stream filtering and preprocessing.Armin Ronacherbefore adoption9ad96e7
line 171why, one step back171 :members: preprocess, filter_stream, parse, attr, call_methodFirst extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9
lines 172–190why, one step back172173 .. 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.Parseradded a function to parse assign targes and documented it for the extension interfaceArmin Ronacherbefore adoption09c002e
line 191why, one step back191 :members: parse_expression, parse_tuple, parse_assign_target,improved exception system. now both name (load name) and filename are passed.Armin Ronacherbefore adoption7f15ef8
line 192why, one step back192 parse_statements, free_identifier, failFirst extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9
lines 193–196why, one step back193194 .. attribute:: filename195196 The filename of the template the parser processes. This is **not**removed attribute local aliasing again because that implementation was brokenArmin Ronacherbefore adoption67fdddf
line 197why, one step back197 the load name of the template. For the load name see :attr:`name`.First extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9
lines 198–199why, one step back198 For templates that were not loaded form the file system this is199 `None`.removed attribute local aliasing again because that implementation was brokenArmin Ronacherbefore adoption67fdddf
lines 200–203why, one step back200201 .. attribute:: name202203 The load name of the template.First extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9
lines 204–209why, one step back204205 .. attribute:: stream206207 The current :class:`~jinja2.lexer.TokenStream`208209.. autoclass:: jinja2.lexer.TokenStreamadded parsing code for "for item in seq recursive" and improved parser interface a bitArmin Ronacherbefore adoptionfdf9530
line 210why, one step back210 :members: push, look, eos, skip, next, next_if, skip_if, expectFirst extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9
lines 211–231why, one step back211212 .. 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.231Added example extension that uses the stream filtering and added unittests.Armin Ronacherbefore adoptiond02fc7d
lines 232–236why, one step back232There is also a utility function in the lexer module that can count newline233characters in strings:234235.. autofunction:: jinja2.lexer.count_newlines236First extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9
lines 237–254why, one step back237AST238~~~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