Skip to content
Myr

extensions.rst

This file

Path

docs/extensions.rst

282 lines · 8.8 KiB

Last changed by

Documented autoescaping behavior and eval contexts.Armin Ronacherbefore adoptionfe150f3

History of this file

Take it

The walk stopped after 200 commits: lines older than 237cdde point at it.

tip is now 2.1-devArmin Ronacherbefore adoption237cdde

lines 1–114why, 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::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.114

added with-statement extension.Armin Ronacherbefore adoption9b4cc9f

lines 115–128why, one step back
115.. _with-extension:
116117With Statement118--------------119120**Import name:** `jinja2.ext.with_`121122.. versionadded:: 2.3123124This extension adds support for the with keyword. Using this keyword it125is possible to enforce a nested scope in a template. Variables can be126declared directly in the opening block of the with statement or using a127standard `set` statement directly within.128

Documented autoescaping behavior and eval contexts.Armin Ronacherbefore adoptionfe150f3

lines 129–142why, one step back
129.. _autoescape-extension:
130131Autoescape Extension132--------------------133134**Import name:** `jinja2.ext.autoescape`135136.. versionadded:: 2.4137138The autoescape extension allows you to toggle the autoescape feature from139within the template. If the environment's :attr:`~Environment.autoescape`140setting is set to `False` it can be activated, if it's `True` it can be141activated. The setting overriding is scoped.142

tip is now 2.1-devArmin Ronacherbefore adoption237cdde

lines 143–282why, one step back
143
144.. _writing-extensions:145146Writing Extensions147------------------148149.. module:: jinja2.ext150151By writing extensions you can add custom tags to Jinja2. This is a non trival152task and usually not needed as the default tags and expressions cover all153common use cases. The i18n extension is a good example of why extensions are154useful, another one would be fragment caching.155156When writing extensions you have to keep in mind that you are working with the157Jinja2 template compiler which does not validate the node tree you are possing158to it. If the AST is malformed you will get all kinds of compiler or runtime159errors that are horrible to debug. Always make sure you are using the nodes160you create correctly. The API documentation below shows which nodes exist and161how to use them.162163Example Extension164~~~~~~~~~~~~~~~~~165166The following example implements a `cache` tag for Jinja2 by using the167`Werkzeug`_ caching contrib module:168169.. literalinclude:: cache_extension.py170 :language: python171172And here is how you use it in an environment::173174 from jinja2 import Environment175 from werkzeug.contrib.cache import SimpleCache176177 env = Environment(extensions=[FragmentCacheExtension])178 env.fragment_cache = SimpleCache()179180Inside the template it's then possible to mark blocks as cacheable. The181following example caches a sidebar for 300 seconds:182183.. sourcecode:: html+jinja184185 {% cache 'sidebar', 300 %}186 <div class="sidebar">187 ...188 </div>189 {% endcache %}190191.. _Werkzeug: http://werkzeug.pocoo.org/192193Extension API194~~~~~~~~~~~~~195196Extensions always have to extend the :class:`jinja2.ext.Extension` class:197198.. autoclass:: Extension199 :members: preprocess, filter_stream, parse, attr, call_method200201 .. attribute:: identifier202203 The identifier of the extension. This is always the true import name204 of the extension class and must not be changed.205206 .. attribute:: tags207208 If the extension implements custom tags this is a set of tag names209 the extension is listening for.210211Parser API212~~~~~~~~~~213214The parser passed to :meth:`Extension.parse` provides ways to parse215expressions of different types. The following methods may be used by216extensions:217218.. autoclass:: jinja2.parser.Parser219 :members: parse_expression, parse_tuple, parse_assign_target,220 parse_statements, free_identifier, fail221222 .. attribute:: filename223224 The filename of the template the parser processes. This is **not**225 the load name of the template. For the load name see :attr:`name`.226 For templates that were not loaded form the file system this is227 `None`.228229 .. attribute:: name230231 The load name of the template.232233 .. attribute:: stream234235 The current :class:`~jinja2.lexer.TokenStream`236237.. autoclass:: jinja2.lexer.TokenStream238 :members: push, look, eos, skip, next, next_if, skip_if, expect239240 .. attribute:: current241242 The current :class:`~jinja2.lexer.Token`.243244.. autoclass:: jinja2.lexer.Token245 :members: test, test_any246247 .. attribute:: lineno248249 The line number of the token250251 .. attribute:: type252253 The type of the token. This string is interned so you may compare254 it with arbitrary strings using the `is` operator.255256 .. attribute:: value257258 The value of the token.259260There is also a utility function in the lexer module that can count newline261characters in strings:262263.. autofunction:: jinja2.lexer.count_newlines264265AST266~~~267268The AST (Abstract Syntax Tree) is used to represent a template after parsing.269It's build of nodes that the compiler then converts into executable Python270code objects. Extensions that provide custom statements can return nodes to271execute custom Python code.272273The list below describes all nodes that are currently available. The AST may274change between Jinja2 versions but will stay backwards compatible.275276For more information have a look at the repr of :meth:`jinja2.Environment.parse`.277278.. module:: jinja2.nodes279280.. jinjanodes::281282.. autoexception:: Impossible