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

some documentation updatesArmin Ronacherbefore adoptioned98cac

lines 1–19why, one step back
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::19

added a function to parse assign targes and documented it for the extension interfaceArmin Ronacherbefore adoption09c002e

line 20why, one step back
20 jinja_env = Environment(extensions=['jinja2.ext.i18n'])

some documentation updatesArmin Ronacherbefore adoptioned98cac

lines 21–24why, one step back
21
2223.. _i18n-extension:24

First extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9

lines 25–26why, one step back
25i18n Extension
26--------------

some documentation updatesArmin Ronacherbefore adoptioned98cac

line 27why, one step back
27

void -> doArmin Ronacherbefore adoption5d2733f

lines 28–29why, one step back
28**Import name:** `jinja2.ext.i18n`
29

First extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9

lines 30–33why, one step back
30Jinja2 currently comes with one extension, the i18n extension. It can be
31used 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 back
34

more updates on the extension APIArmin Ronacherbefore adoption762079c

lines 35–38why, one step back
35After enabling dummy `_` function that forwards calls to `gettext` is added
36to 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 back
39

more updates on the extension APIArmin Ronacherbefore adoption762079c

lines 40–75why, one step back
40After enabling of the extension the environment provides the following
41additional 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.75

some documentation updatesArmin Ronacherbefore adoptioned98cac

lines 76–81why, one step back
76For a web application that is available in multiple languages but gives all
77the 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 back
82 env = Environment(extensions=['jinja2.ext.i18n'])

more updates on the extension APIArmin Ronacherbefore adoption762079c

line 83why, one step back
83 env.install_gettext_translations(translations)

some documentation updatesArmin Ronacherbefore adoptioned98cac

lines 84–85why, one step back
84
85The `get_gettext_translations` function would return the translator for the

more updates on the extension APIArmin Ronacherbefore adoption762079c

line 86why, one step back
86current configuration. (For example by using `gettext.find`)

some documentation updatesArmin Ronacherbefore adoptioned98cac

lines 87–91why, one step back
87
88The 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/gettext

more updates on the extension APIArmin Ronacherbefore adoption762079c

line 92why, one step back
92.. _Babel: http://babel.edgewall.org/

void -> doArmin Ronacherbefore adoption5d2733f

lines 93–94why, one step back
93
94

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 95–96why, one step back
95Expression Statement
96--------------------

void -> doArmin Ronacherbefore adoption5d2733f

lines 97–99why, one step back
97
98**Import name:** `jinja2.ext.do`99

more 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 back
100The "do" aka expression-statement extension adds a simple `do` tag to the

void -> doArmin Ronacherbefore adoption5d2733f

lines 101–102why, one step back
101template engine that works like a variable expression but ignores the
102return value.

some documentation updatesArmin Ronacherbefore adoptioned98cac

line 103why, one step back
103

added loopcontrols extension and added unittests for itArmin Ronacherbefore adoption3da9031

lines 104–105why, one step back
104.. _loopcontrols-extension:
105

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 106–107why, one step back
106Loop Controls
107-------------

added loopcontrols extension and added unittests for itArmin Ronacherbefore adoption3da9031

lines 108–114why, one step back
108
109**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.114

First extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9

line 115why, one step back
115

some documentation updatesArmin Ronacherbefore adoptioned98cac

lines 116–120why, one step back
116.. _writing-extensions:
117118Writing Extensions119------------------120

more updates on the extension APIArmin Ronacherbefore adoption762079c

lines 121–122why, one step back
121.. module:: jinja2.ext
122

First extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9

lines 123–127why, one step back
123By writing extensions you can add custom tags to Jinja2. This is a non trival
124task 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.127

added support for dotted names in tests and filtersArmin Ronacherbefore adoptionb9e7875

lines 128–134why, one step back
128When writing extensions you have to keep in mind that you are working with the
129Jinja2 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.134

First extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9

lines 135–137why, one step back
135Example Extension
136~~~~~~~~~~~~~~~~~137

more updates on the extension APIArmin Ronacherbefore adoption762079c

lines 138–139why, one step back
138The following example implements a `cache` tag for Jinja2 by using the
139`Werkzeug`_ caching contrib module:

First extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9

lines 140–143why, one step back
140
141.. literalinclude:: cache_extension.py142 :language: python143

more updates on the extension APIArmin Ronacherbefore adoption762079c

line 144why, one step back
144And 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 back
145
146 from jinja2 import Environment147 from werkzeug.contrib.cache import SimpleCache148

more updates on the extension APIArmin Ronacherbefore adoption762079c

lines 149–150why, one step back
149 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 back
151
152Inside 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 back
162
163.. _Werkzeug: http://werkzeug.pocoo.org/164165Extension API166~~~~~~~~~~~~~167168Extensions always have to extend the :class:`jinja2.ext.Extension` class:169170.. autoclass:: Extension

added support for token stream filtering and preprocessing.Armin Ronacherbefore adoption9ad96e7

line 171why, one step back
171 :members: preprocess, filter_stream, parse, attr, call_method

First extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9

lines 172–190why, one step back
172
173 .. 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.Parser

added a function to parse assign targes and documented it for the extension interfaceArmin Ronacherbefore adoption09c002e

line 191why, one step back
191 :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 back
192 parse_statements, free_identifier, fail

First extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9

lines 193–196why, one step back
193
194 .. 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 back
197 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 back
198 For templates that were not loaded form the file system this is
199 `None`.

removed attribute local aliasing again because that implementation was brokenArmin Ronacherbefore adoption67fdddf

lines 200–203why, one step back
200
201 .. attribute:: name202203 The load name of the template.

First extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9

lines 204–209why, one step back
204
205 .. attribute:: stream206207 The current :class:`~jinja2.lexer.TokenStream`208209.. autoclass:: jinja2.lexer.TokenStream

added parsing code for "for item in seq recursive" and improved parser interface a bitArmin Ronacherbefore adoptionfdf9530

line 210why, one step back
210 :members: push, look, eos, skip, next, next_if, skip_if, expect

First extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9

lines 211–231why, one step back
211
212 .. 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.231

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

lines 232–236why, one step back
232There is also a utility function in the lexer module that can count newline
233characters in strings:234235.. autofunction:: jinja2.lexer.count_newlines236

First extension interface documentation and updates in that interfaceArmin Ronacherbefore adoption023b5e9

lines 237–254why, one step back
237AST
238~~~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