extensions.rst
This file
Path
docs/extensions.rst
346 lines · 11.1 KiB
Last changed by
Merge branch 'master' of github.com:mitsuhiko/jinja2Armin Ronacherbefore adoption67d015e
History of this fileTake 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 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`extensions` 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`2930The i18n extension can be used in combination with `gettext`_ or `babel`_. If 31the i18n extension is enabled Jinja2 provides a `trans` statement that marks 32the wrapped string as translatable and calls `gettext`.3334After enabling, dummy `_` function that forwards calls to `gettext` is added35to the environment globals. An internationalized application then has to36provide a `gettext` function and optionally an `ngettext` function into the37namespace, either globally or for each rendering.3839Environment Methods40~~~~~~~~~~~~~~~~~~~4142After enabling the extension, the environment provides the following43additional methods:4445.. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)4647 Installs a translation globally for that environment. The translations48 object provided must implement at least `ugettext` and `ungettext`.49 The `gettext.NullTranslations` and `gettext.GNUTranslations` classes50 as well as `Babel`_\s `Translations` class are supported.5152 .. versionchanged:: 2.5 newstyle gettext added5354.. method:: jinja2.Environment.install_null_translations(newstyle=False)5556 Install dummy gettext functions. This is useful if you want to prepare57 the application for internationalization but don't want to implement the58 full internationalization system yet.5960 .. versionchanged:: 2.5 newstyle gettext added6162.. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False)6364 Installs the given `gettext` and `ngettext` callables into the65 environment as globals. They are supposed to behave exactly like the66 standard library's :func:`gettext.ugettext` and67 :func:`gettext.ungettext` functions.6869 If `newstyle` is activated, the callables are wrapped to work like70 newstyle callables. See :ref:`newstyle-gettext` for more information.7172 .. versionadded:: 2.57374.. method:: jinja2.Environment.uninstall_gettext_translations()7576 Uninstall the translations again.7778.. method:: jinja2.Environment.extract_translations(source)7980 Extract localizable strings from the given template node or source.8182 For every string found this function yields a ``(lineno, function,83 message)`` tuple, where:8485 * `lineno` is the number of the line on which the string was found,86 * `function` is the name of the `gettext` function used (if the87 string was extracted from embedded Python code), and88 * `message` is the string itself (a `unicode` object, or a tuple89 of `unicode` objects for functions with multiple string arguments).9091 If `Babel`_ is installed, :ref:`the babel integration <babel-integration>`92 can be used to extract strings for babel.9394For a web application that is available in multiple languages but gives all95the users the same language (for example a multilingual forum software96installed for a French community) may load the translations once and add the97translation methods to the environment at environment generation time::9899 translations = get_gettext_translations()100 env = Environment(extensions=['jinja2.ext.i18n'])101 env.install_gettext_translations(translations)102103The `get_gettext_translations` function would return the translator for the104current configuration. (For example by using `gettext.find`)105106The usage of the `i18n` extension for template designers is covered as part107:ref:`of the template documentation <i18n-in-templates>`.108109.. _gettext: http://docs.python.org/dev/library/gettext110.. _Babel: http://babel.pocoo.org/111112.. _newstyle-gettext:113114Newstyle Gettext115~~~~~~~~~~~~~~~~116117.. versionadded:: 2.5118119Starting with version 2.5 you can use newstyle gettext calls. These are120inspired by trac's internal gettext functions and are fully supported by121the babel extraction tool. They might not work as expected by other122extraction tools in case you are not using Babel's.123124What's the big difference between standard and newstyle gettext calls? In125general they are less to type and less error prone. Also if they are used126in an autoescaping environment they better support automatic escaping.127Here are some common differences between old and new calls:128129standard gettext:130131.. sourcecode:: html+jinja132133 {{ gettext('Hello World!') }}134 {{ gettext('Hello %(name)s!')|format(name='World') }}135 {{ ngettext('%(num)d apple', '%(num)d apples', apples|count)|format(136 num=apples|count137 )}}138139newstyle gettext looks like this instead:140141.. sourcecode:: html+jinja142143 {{ gettext('Hello World!') }}144 {{ gettext('Hello %(name)s!', name='World') }}145 {{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }}146147The advantages of newstyle gettext are that you have less to type and that148named placeholders become mandatory. The latter sounds like a149disadvantage but solves a lot of troubles translators are often facing150when they are unable to switch the positions of two placeholder. With151newstyle gettext, all format strings look the same.152153Furthermore with newstyle gettext, string formatting is also used if no154placeholders are used which makes all strings behave exactly the same.155Last but not least are newstyle gettext calls able to properly mark156strings for autoescaping which solves lots of escaping related issues many157templates are experiencing over time when using autoescaping.158159Expression Statement160--------------------161162**Import name:** `jinja2.ext.do`163164The "do" aka expression-statement extension adds a simple `do` tag to the165template engine that works like a variable expression but ignores the166return value.167168.. _loopcontrols-extension:169170Loop Controls171-------------172173**Import name:** `jinja2.ext.loopcontrols`174175This extension adds support for `break` and `continue` in loops. After176enabling, Jinja2 provides those two keywords which work exactly like in177Python.178179.. _with-extension:180181With Statement182--------------183184**Import name:** `jinja2.ext.with_`185186.. versionadded:: 2.3187188This extension adds support for the with keyword. Using this keyword it189is possible to enforce a nested scope in a template. Variables can be190declared directly in the opening block of the with statement or using a191standard `set` statement directly within.192193.. _autoescape-extension:194195Autoescape Extension196--------------------197198**Import name:** `jinja2.ext.autoescape`199200.. versionadded:: 2.4201202The autoescape extension allows you to toggle the autoescape feature from203within the template. If the environment's :attr:`~Environment.autoescape`204setting is set to `False` it can be activated, if it's `True` it can be205deactivated. The setting overriding is scoped.206207208.. _writing-extensions:209210Writing Extensions211------------------212213.. module:: jinja2.ext214215By writing extensions you can add custom tags to Jinja2. This is a non-trivial216task and usually not needed as the default tags and expressions cover all217common use cases. The i18n extension is a good example of why extensions are218useful. Another one would be fragment caching.219220When writing extensions you have to keep in mind that you are working with the221Jinja2 template compiler which does not validate the node tree you are passing222to it. If the AST is malformed you will get all kinds of compiler or runtime223errors that are horrible to debug. Always make sure you are using the nodes224you create correctly. The API documentation below shows which nodes exist and225how to use them.226227Example Extension228~~~~~~~~~~~~~~~~~229230The following example implements a `cache` tag for Jinja2 by using the231`Werkzeug`_ caching contrib module:232233.. literalinclude:: cache_extension.py234 :language: python235236And here is how you use it in an environment::237238 from jinja2 import Environment239 from werkzeug.contrib.cache import SimpleCache240241 env = Environment(extensions=[FragmentCacheExtension])242 env.fragment_cache = SimpleCache()243244Inside the template it's then possible to mark blocks as cacheable. The245following example caches a sidebar for 300 seconds:246247.. sourcecode:: html+jinja248249 {% cache 'sidebar', 300 %}250 <div class="sidebar">251 ...252 </div>253 {% endcache %}254255.. _Werkzeug: http://werkzeug.pocoo.org/256257Extension API258~~~~~~~~~~~~~259260Extensions always have to extend the :class:`jinja2.ext.Extension` class:261262.. autoclass:: Extension263 :members: preprocess, filter_stream, parse, attr, call_method264265 .. attribute:: identifier266267 The identifier of the extension. This is always the true import name268 of the extension class and must not be changed.269270 .. attribute:: tags271272 If the extension implements custom tags this is a set of tag names273 the extension is listening for.274275Parser API276~~~~~~~~~~277278The parser passed to :meth:`Extension.parse` provides ways to parse279expressions of different types. The following methods may be used by280extensions:281282.. autoclass:: jinja2.parser.Parser283 :members: parse_expression, parse_tuple, parse_assign_target,284 parse_statements, free_identifier, fail285286 .. attribute:: filename287288 The filename of the template the parser processes. This is **not**289 the load name of the template. For the load name see :attr:`name`.290 For templates that were not loaded form the file system this is291 `None`.292293 .. attribute:: name294295 The load name of the template.296297 .. attribute:: stream298299 The current :class:`~jinja2.lexer.TokenStream`300301.. autoclass:: jinja2.lexer.TokenStream302 :members: push, look, eos, skip, next, next_if, skip_if, expect303304 .. attribute:: current305306 The current :class:`~jinja2.lexer.Token`.307308.. autoclass:: jinja2.lexer.Token309 :members: test, test_any310311 .. attribute:: lineno312313 The line number of the token314315 .. attribute:: type316317 The type of the token. This string is interned so you may compare318 it with arbitrary strings using the `is` operator.319320 .. attribute:: value321322 The value of the token.323324There is also a utility function in the lexer module that can count newline325characters in strings:326327.. autofunction:: jinja2.lexer.count_newlines328329AST330~~~331332The AST (Abstract Syntax Tree) is used to represent a template after parsing.333It's build of nodes that the compiler then converts into executable Python334code objects. Extensions that provide custom statements can return nodes to335execute custom Python code.336337The list below describes all nodes that are currently available. The AST may338change between Jinja2 versions but will stay backwards compatible.339340For more information have a look at the repr of :meth:`jinja2.Environment.parse`.341342.. module:: jinja2.nodes343344.. jinjanodes::345346.. autoexception:: Impossible