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
The walk stopped after 200 commits: lines older than 41746b9 point at it.
Some more small cleanup for metaclassesArmin Ronacherbefore adoption41746b9
lines 1–6why, one step back1.. _jinja-extensions:23Extensions4==========56Jinja2 supports extensions that can add extra filters, tests, globals or evenMerge pull request #284 from LucianU/patch-1Armin Ronacherbefore adoption0d52d72
line 7why, one step back7extend the parser. The main motivation of extensions is to move often usedSome more small cleanup for metaclassesArmin Ronacherbefore adoption41746b9
lines 8–16why, one step back8code 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 theMerge pull request #284 from LucianU/patch-1Armin Ronacherbefore adoption0d52d72
line 17why, one step back17`extensions` parameter of the :class:`Environment` constructor. The followingSome more small cleanup for metaclassesArmin Ronacherbefore adoption41746b9
lines 18–29why, one step back18example 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`29Merge pull request #403 from whit537/patch-1Markus Unterwaditzerbefore adoption242cd2c
lines 30–32why, one step back30The 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`.Some more small cleanup for metaclassesArmin Ronacherbefore adoption41746b9
line 33why, one step back33Merge pull request #284 from LucianU/patch-1Armin Ronacherbefore adoption0d52d72
line 34why, one step back34After enabling, dummy `_` function that forwards calls to `gettext` is addedSome more small cleanup for metaclassesArmin Ronacherbefore adoption41746b9
line 35why, one step back35to the environment globals. An internationalized application then has toMerge pull request #284 from LucianU/patch-1Armin Ronacherbefore adoption0d52d72
lines 36–37why, one step back36provide a `gettext` function and optionally an `ngettext` function into the37namespace, either globally or for each rendering.Some more small cleanup for metaclassesArmin Ronacherbefore adoption41746b9
lines 38–41why, one step back3839Environment Methods40~~~~~~~~~~~~~~~~~~~41Merge pull request #284 from LucianU/patch-1Armin Ronacherbefore adoption0d52d72
line 42why, one step back42After enabling the extension, the environment provides the followingSome more small cleanup for metaclassesArmin Ronacherbefore adoption41746b9
lines 43–46why, one step back43additional methods:4445.. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)46Merge pull request #284 from LucianU/patch-1Armin Ronacherbefore adoption0d52d72
line 47why, one step back47 Installs a translation globally for that environment. The translationsSome more small cleanup for metaclassesArmin Ronacherbefore adoption41746b9
lines 48–90why, one step back48 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).90Merge pull request #284 from LucianU/patch-1Armin Ronacherbefore adoption0d52d72
line 91why, one step back91 If `Babel`_ is installed, :ref:`the babel integration <babel-integration>`Some more small cleanup for metaclassesArmin Ronacherbefore adoption41746b9
lines 92–109why, one step back92 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/gettextMerge branch 'master' of github.com:mitsuhiko/jinja2Armin Ronacherbefore adoption67d015e
line 110why, one step back110.. _Babel: http://babel.pocoo.org/Some more small cleanup for metaclassesArmin Ronacherbefore adoption41746b9
lines 111–126why, one step back111112.. _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.Merge pull request #284 from LucianU/patch-1Armin Ronacherbefore adoption0d52d72
line 127why, one step back127Here are some common differences between old and new calls:Some more small cleanup for metaclassesArmin Ronacherbefore adoption41746b9
lines 128–146why, one step back128129standard 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) }}146Merge pull request #284 from LucianU/patch-1Armin Ronacherbefore adoption0d52d72
line 147why, one step back147The advantages of newstyle gettext are that you have less to type and thatSome more small cleanup for metaclassesArmin Ronacherbefore adoption41746b9
lines 148–175why, one step back148named 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. AfterMerge pull request #284 from LucianU/patch-1Armin Ronacherbefore adoption0d52d72
line 176why, one step back176enabling, Jinja2 provides those two keywords which work exactly like inSome more small cleanup for metaclassesArmin Ronacherbefore adoption41746b9
lines 177–214why, one step back177Python.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.ext214Merge pull request #230 from p1otr/masterArmin Ronacherbefore adoptionc97fa10
line 215why, one step back215By writing extensions you can add custom tags to Jinja2. This is a non-trivialSome more small cleanup for metaclassesArmin Ronacherbefore adoption41746b9
lines 216–217why, one step back216task and usually not needed as the default tags and expressions cover all217common use cases. The i18n extension is a good example of why extensions areMerge pull request #284 from LucianU/patch-1Armin Ronacherbefore adoption0d52d72
line 218why, one step back218useful. Another one would be fragment caching.Some more small cleanup for metaclassesArmin Ronacherbefore adoption41746b9
lines 219–346why, one step back219220When 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