1.. _jinja-extensions: 2 3Extensions 4========== 5 6Jinja supports extensions that can add extra filters, tests, globals or even 7extend the parser. The main motivation of extensions is to move often used 8code into a reusable class like adding support for internationalization. 9 10 11Adding Extensions 12----------------- 13 14Extensions are added to the Jinja environment at creation time. Once the 15environment is created additional extensions cannot be added. To add an 16extension pass a list of extension classes or import paths to the 17``extensions`` parameter of the :class:`~jinja2.Environment` constructor. The following 18example creates a Jinja environment with the i18n extension loaded:: 19 20 jinja_env = Environment(extensions=['jinja2.ext.i18n']) 21 22 23.. _i18n-extension: 24 25i18n Extension 26-------------- 27 28**Import name:** ``jinja2.ext.i18n`` 29 30The i18n extension can be used in combination with `gettext`_ or 31`Babel`_. When it's enabled, Jinja provides a ``trans`` statement that 32marks a block as translatable and calls ``gettext``. 33 34After enabling, an application has to provide ``gettext`` and 35``ngettext`` functions, either globally or when rendering. A ``_()`` 36function is added as an alias to the ``gettext`` function. 37 38Environment Methods 39~~~~~~~~~~~~~~~~~~~ 40 41After enabling the extension, the environment provides the following 42additional methods: 43 44.. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False) 45 46 Installs a translation globally for the environment. The 47 ``translations`` object must implement ``gettext`` and ``ngettext``. 48 :class:`gettext.NullTranslations`, :class:`gettext.GNUTranslations`, 49 and `Babel`_\s ``Translations`` are supported. 50 51 .. versionchanged:: 2.5 Added new-style gettext support. 52 53.. method:: jinja2.Environment.install_null_translations(newstyle=False) 54 55 Install no-op gettext functions. This is useful if you want to 56 prepare the application for internationalization but don't want to 57 implement the full system yet. 58 59 .. versionchanged:: 2.5 Added new-style gettext support. 60 61.. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False) 62 63 Install the given ``gettext`` and ``ngettext`` callables into the 64 environment. They should behave exactly like 65 :func:`gettext.gettext` and :func:`gettext.ngettext`. 66 67 If ``newstyle`` is activated, the callables are wrapped to work like 68 newstyle callables. See :ref:`newstyle-gettext` for more information. 69 70 .. versionadded:: 2.5 Added new-style gettext support. 71 72.. method:: jinja2.Environment.uninstall_gettext_translations() 73 74 Uninstall the environment's globally installed translation. 75 76.. method:: jinja2.Environment.extract_translations(source) 77 78 Extract localizable strings from the given template node or source. 79 80 For every string found this function yields a ``(lineno, function, 81 message)`` tuple, where: 82 83 - ``lineno`` is the number of the line on which the string was 84 found. 85 - ``function`` is the name of the ``gettext`` function used (if 86 the string was extracted from embedded Python code). 87 - ``message`` is the string itself, or a tuple of strings for 88 functions with multiple arguments. 89 90 If `Babel`_ is installed, see :ref:`babel-integration` to extract 91 the strings. 92 93For a web application that is available in multiple languages but gives 94all the users the same language (for example, multilingual forum 95software installed for a French community), the translation may be 96installed when the environment is created. 97 98.. code-block:: python 99 100 translations = get_gettext_translations() 101 env = Environment(extensions=["jinja2.ext.i18n"]) 102 env.install_gettext_translations(translations) 103 104The ``get_gettext_translations`` function would return the translator 105for the current configuration, for example by using ``gettext.find``. 106 107The usage of the ``i18n`` extension for template designers is covered in 108:ref:`the template documentation <i18n-in-templates>`. 109 110.. _gettext: https://docs.python.org/3/library/gettext.html 111.. _Babel: http://babel.pocoo.org/ 112 113 114Whitespace Trimming 115~~~~~~~~~~~~~~~~~~~ 116 117.. versionadded:: 2.10 118 119Within ``{% trans %}`` blocks, it can be useful to trim line breaks and 120whitespace so that the block of text looks like a simple string with 121single spaces in the translation file. 122 123Linebreaks and surrounding whitespace can be automatically trimmed by 124enabling the ``ext.i18n.trimmed`` :ref:`policy <ext-i18n-trimmed>`. 125 126 127.. _newstyle-gettext: 128 129New Style Gettext 130~~~~~~~~~~~~~~~~~ 131 132.. versionadded:: 2.5 133 134New style gettext calls are less to type, less error prone, and support 135autoescaping better. 136 137You can use "new style" gettext calls by setting 138``env.newstyle_gettext = True`` or passing ``newstyle=True`` to 139``env.install_translations``. They are fully supported by the Babel 140extraction tool, but might not work as expected with other extraction 141tools. 142 143With standard ``gettext`` calls, string formatting is a separate step 144done with the ``|format`` filter. This requires duplicating work for 145``ngettext`` calls. 146 147.. sourcecode:: jinja 148 149 {{ gettext("Hello, World!") }} 150 {{ gettext("Hello, %(name)s!")|format(name=name) }} 151 {{ ngettext( 152 "%(num)d apple", "%(num)d apples", apples|count 153 )|format(num=apples|count) }} 154 155New style ``gettext`` make formatting part of the call, and behind the 156scenes enforce more consistency. 157 158.. sourcecode:: jinja 159 160 {{ gettext("Hello, World!") }} 161 {{ gettext("Hello, %(name)s!", name=name) }} 162 {{ ngettext("%(num)d apple", "%(num)d apples", apples|count) }} 163 164The advantages of newstyle gettext are: 165 166- There's no separate formatting step, you don't have to remember to 167 use the ``|format`` filter. 168- Only named placeholders are allowed. This solves a common problem 169 translators face because positional placeholders can't switch 170 positions meaningfully. Named placeholders always carry semantic 171 information about what value goes where. 172- String formatting is used even if no placeholders are used, which 173 makes all strings use a consistent format. Remember to escape any 174 raw percent signs as ``%%``, such as ``100%%``. 175- The translated string is marked safe, formatting performs escaping 176 as needed. Mark a parameter as ``|safe`` if it has already been 177 escaped. 178 179 180Expression Statement 181-------------------- 182 183**Import name:** ``jinja2.ext.do`` 184 185The "do" aka expression-statement extension adds a simple ``do`` tag to the 186template engine that works like a variable expression but ignores the 187return value. 188 189.. _loopcontrols-extension: 190 191Loop Controls 192------------- 193 194**Import name:** ``jinja2.ext.loopcontrols`` 195 196This extension adds support for ``break`` and ``continue`` in loops. After 197enabling, Jinja provides those two keywords which work exactly like in 198Python. 199 200.. _with-extension: 201 202With Statement 203-------------- 204 205**Import name:** ``jinja2.ext.with_`` 206 207.. versionchanged:: 2.9 208 209 This extension is now built-in and no longer does anything. 210 211.. _autoescape-extension: 212 213Autoescape Extension 214-------------------- 215 216**Import name:** ``jinja2.ext.autoescape`` 217 218.. versionchanged:: 2.9 219 220 This extension was removed and is now built-in. Enabling the 221 extension no longer does anything. 222 223 224.. _debug-extension: 225 226Debug Extension 227--------------- 228 229**Import name:** ``jinja2.ext.debug`` 230 231Adds a ``{% debug %}`` tag to dump the current context as well as the 232available filters and tests. This is useful to see what's available to 233use in the template without setting up a debugger. 234 235 236.. _writing-extensions: 237 238Writing Extensions 239------------------ 240 241.. module:: jinja2.ext 242 243By writing extensions you can add custom tags to Jinja. This is a non-trivial 244task and usually not needed as the default tags and expressions cover all 245common use cases. The i18n extension is a good example of why extensions are 246useful. Another one would be fragment caching. 247 248When writing extensions you have to keep in mind that you are working with the 249Jinja template compiler which does not validate the node tree you are passing 250to it. If the AST is malformed you will get all kinds of compiler or runtime 251errors that are horrible to debug. Always make sure you are using the nodes 252you create correctly. The API documentation below shows which nodes exist and 253how to use them. 254 255 256Example Extensions 257------------------ 258 259Cache 260~~~~~ 261 262The following example implements a ``cache`` tag for Jinja by using the 263`cachelib`_ library: 264 265.. literalinclude:: examples/cache_extension.py 266 :language: python 267 268And here is how you use it in an environment:: 269 270 from jinja2 import Environment 271 from cachelib import SimpleCache 272 273 env = Environment(extensions=[FragmentCacheExtension]) 274 env.fragment_cache = SimpleCache() 275 276Inside the template it's then possible to mark blocks as cacheable. The 277following example caches a sidebar for 300 seconds: 278 279.. sourcecode:: html+jinja 280 281 {% cache 'sidebar', 300 %} 282 <div class="sidebar"> 283 ... 284 </div> 285 {% endcache %} 286 287.. _cachelib: https://github.com/pallets/cachelib 288 289 290Inline ``gettext`` 291~~~~~~~~~~~~~~~~~~ 292 293The following example demonstrates using :meth:`Extension.filter_stream` 294to parse calls to the ``_()`` gettext function inline with static data 295without needing Jinja blocks. 296 297.. code-block:: html 298 299 <h1>_(Welcome)</h1> 300 <p>_(This is a paragraph)</p> 301 302It requires the i18n extension to be loaded and configured. 303 304.. literalinclude:: examples/inline_gettext_extension.py 305 :language: python 306 307 308Extension API 309------------- 310 311Extension 312~~~~~~~~~ 313 314Extensions always have to extend the :class:`jinja2.ext.Extension` class: 315 316.. autoclass:: Extension 317 :members: preprocess, filter_stream, parse, attr, call_method 318 319 .. attribute:: identifier 320 321 The identifier of the extension. This is always the true import name 322 of the extension class and must not be changed. 323 324 .. attribute:: tags 325 326 If the extension implements custom tags this is a set of tag names 327 the extension is listening for. 328 329 330Parser 331~~~~~~ 332 333The parser passed to :meth:`Extension.parse` provides ways to parse 334expressions of different types. The following methods may be used by 335extensions: 336 337.. autoclass:: jinja2.parser.Parser 338 :members: parse_expression, parse_tuple, parse_assign_target, 339 parse_statements, free_identifier, fail 340 341 .. attribute:: filename 342 343 The filename of the template the parser processes. This is **not** 344 the load name of the template. For the load name see :attr:`name`. 345 For templates that were not loaded form the file system this is 346 ``None``. 347 348 .. attribute:: name 349 350 The load name of the template. 351 352 .. attribute:: stream 353 354 The current :class:`~jinja2.lexer.TokenStream` 355 356.. autoclass:: jinja2.lexer.TokenStream 357 :members: push, look, eos, skip, __next__, next_if, skip_if, expect 358 359 .. attribute:: current 360 361 The current :class:`~jinja2.lexer.Token`. 362 363.. autoclass:: jinja2.lexer.Token 364 :members: test, test_any 365 366 .. attribute:: lineno 367 368 The line number of the token 369 370 .. attribute:: type 371 372 The type of the token. This string is interned so you may compare 373 it with arbitrary strings using the ``is`` operator. 374 375 .. attribute:: value 376 377 The value of the token. 378 379There is also a utility function in the lexer module that can count newline 380characters in strings: 381 382.. autofunction:: jinja2.lexer.count_newlines 383 384 385AST 386~~~ 387 388The AST (Abstract Syntax Tree) is used to represent a template after parsing. 389It's build of nodes that the compiler then converts into executable Python 390code objects. Extensions that provide custom statements can return nodes to 391execute custom Python code. 392 393The list below describes all nodes that are currently available. The AST may 394change between Jinja versions but will stay backwards compatible. 395 396For more information have a look at the repr of :meth:`jinja2.Environment.parse`. 397 398.. module:: jinja2.nodes 399 400.. jinja:nodes:: jinja2.nodes.Node 401 402.. autoexception:: Impossible 403