6 Jinja2 supports extensions that can add extra filters, tests, globals or even
7 extend the parser. The main motivation of extensions is it to move often used
8 code into a reusable class like adding support for internationalization.
14 Extensions are added to the Jinja2 environment at creation time. Once the
15 environment is created additional extensions cannot be added. To add an
16 extension pass a list of extension classes or import paths to the
17 `environment` parameter of the :class:`Environment` constructor. The following
18 example creates a Jinja2 environment with the i18n extension loaded::
20 jinja_env = Environment(extensions=['jinja2.ext.i18n'])
28 **Import name:** `jinja2.ext.i18n`
30 Jinja2 currently comes with one extension, the i18n extension. It can be
31 used in combination with `gettext`_ or `babel`_. If the i18n extension is
32 enabled Jinja2 provides a `trans` statement that marks the wrapped string as
33 translatable and calls `gettext`.
35 After enabling dummy `_` function that forwards calls to `gettext` is added
36 to the environment globals. An internationalized application then has to
37 provide at least an `gettext` and optoinally a `ngettext` function into the
38 namespace. Either globally or for each rendering.
40 After enabling of the extension the environment provides the following
43 .. method:: jinja2.Environment.install_gettext_translations(translations)
45 Installs a translation globally for that environment. The tranlations
46 object provided must implement at least `ugettext` and `ungettext`.
47 The `gettext.NullTranslations` and `gettext.GNUTranslations` classes
48 as well as `Babel`_\s `Translations` class are supported.
50 .. method:: jinja2.Environment.install_null_translations()
52 Install dummy gettext functions. This is useful if you want to prepare
53 the application for internationalization but don't want to implement the
54 full internationalization system yet.
56 .. method:: jinja2.Environment.uninstall_gettext_translations()
58 Uninstall the translations again.
60 .. method:: jinja2.Environment.extract_translations(source)
62 Extract localizable strings from the given template node or source.
64 For every string found this function yields a ``(lineno, function,
65 message)`` tuple, where:
67 * `lineno` is the number of the line on which the string was found,
68 * `function` is the name of the `gettext` function used (if the
69 string was extracted from embedded Python code), and
70 * `message` is the string itself (a `unicode` object, or a tuple
71 of `unicode` objects for functions with multiple string arguments).
73 If `Babel`_ is installed :ref:`the babel integration <babel-integration>`
74 can be used to extract strings for babel.
76 For a web application that is available in multiple languages but gives all
77 the users the same language (for example a multilingual forum software
78 installed for a French community) may load the translations once and add the
79 translation methods to the environment at environment generation time::
81 translations = get_gettext_translations()
82 env = Environment(extensions=['jinja2.ext.i18n'])
83 env.install_gettext_translations(translations)
85 The `get_gettext_translations` function would return the translator for the
86 current configuration. (For example by using `gettext.find`)
88 The usage of the `i18n` extension for template designers is covered as part
89 :ref:`of the template documentation <i18n-in-templates>`.
91 .. _gettext: http://docs.python.org/dev/library/gettext
92 .. _Babel: http://babel.edgewall.org/
98 **Import name:** `jinja2.ext.do`
100 The "do" aka expression-statement extension adds a simple `do` tag to the
101 template engine that works like a variable expression but ignores the
104 .. _loopcontrols-extension:
109 **Import name:** `jinja2.ext.loopcontrols`
111 This extension adds support for `break` and `continue` in loops. After
112 enabling Jinja2 provides those two keywords which work exactly like in
116 .. _writing-extensions:
121 .. module:: jinja2.ext
123 By writing extensions you can add custom tags to Jinja2. This is a non trival
124 task and usually not needed as the default tags and expressions cover all
125 common use cases. The i18n extension is a good example of why extensions are
126 useful, another one would be fragment caching.
128 When writing extensions you have to keep in mind that you are working with the
129 Jinja2 template compiler which does not validate the node tree you are possing
130 to it. If the AST is malformed you will get all kinds of compiler or runtime
131 errors that are horrible to debug. Always make sure you are using the nodes
132 you create correctly. The API documentation below shows which nodes exist and
138 The following example implements a `cache` tag for Jinja2 by using the
139 `Werkzeug`_ caching contrib module:
141 .. literalinclude:: cache_extension.py
144 And here is how you use it in an environment::
146 from jinja2 import Environment
147 from werkzeug.contrib.cache import SimpleCache
149 env = Environment(extensions=[FragmentCacheExtension])
150 env.fragment_cache = SimpleCache()
152 Inside the template it's then possible to mark blocks as cacheable. The
153 following example caches a sidebar for 300 seconds:
155 .. sourcecode:: html+jinja
157 {% cache 'sidebar', 300 %}
158 <div class="sidebar">
163 .. _Werkzeug: http://werkzeug.pocoo.org/
168 Extensions always have to extend the :class:`jinja2.ext.Extension` class:
170 .. autoclass:: Extension
171 :members: parse, attr, call_method
173 .. attribute:: identifier
175 The identifier of the extension. This is always the true import name
176 of the extension class and must not be changed.
180 If the extension implements custom tags this is a set of tag names
181 the extension is listening for.
186 The parser passed to :meth:`Extension.parse` provides ways to parse
187 expressions of different types. The following methods may be used by
190 .. autoclass:: jinja2.parser.Parser
191 :members: parse_expression, parse_tuple, parse_assign_target,
192 parse_statements, free_identifier, fail
194 .. attribute:: filename
196 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 is
203 The load name of the template.
205 .. attribute:: stream
207 The current :class:`~jinja2.lexer.TokenStream`
209 .. autoclass:: jinja2.lexer.TokenStream
210 :members: push, look, eos, skip, next, next_if, skip_if, expect
212 .. attribute:: current
214 The current :class:`~jinja2.lexer.Token`.
216 .. autoclass:: jinja2.lexer.Token
217 :members: test, test_any
219 .. attribute:: lineno
221 The line number of the token
225 The type of the token. This string is interned so you may compare
226 it with arbitrary strings using the `is` operator.
230 The value of the token.
235 The AST (Abstract Syntax Tree) is used to represent a template after parsing.
236 It's build of nodes that the compiler then converts into executable Python
237 code objects. Extensions that provide custom statements can return nodes to
238 execute custom Python code.
240 The list below describes all nodes that are currently available. The AST may
241 change between Jinja2 versions but will stay backwards compatible.
243 For more information have a look at the repr of :meth:`jinja2.Environment.parse`.
245 .. module:: jinja2.nodes
249 .. autoexception:: Impossible