extensions.rst 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. .. _jinja-extensions:
  2. Extensions
  3. ==========
  4. Jinja2 supports extensions that can add extra filters, tests, globals or even
  5. extend the parser. The main motivation of extensions is it to move often used
  6. code into a reusable class like adding support for internationalization.
  7. Adding Extensions
  8. -----------------
  9. Extensions are added to the Jinja2 environment at creation time. Once the
  10. environment is created additional extensions cannot be added. To add an
  11. extension pass a list of extension classes or import paths to the
  12. `environment` parameter of the :class:`Environment` constructor. The following
  13. example creates a Jinja2 environment with the i18n extension loaded::
  14. jinja_env = Environment(extensions=['jinja2.ext.i18n'])
  15. .. _i18n-extension:
  16. i18n Extension
  17. --------------
  18. **Import name:** `jinja2.ext.i18n`
  19. Jinja2 currently comes with one extension, the i18n extension. It can be
  20. used in combination with `gettext`_ or `babel`_. If the i18n extension is
  21. enabled Jinja2 provides a `trans` statement that marks the wrapped string as
  22. translatable and calls `gettext`.
  23. After enabling dummy `_` function that forwards calls to `gettext` is added
  24. to the environment globals. An internationalized application then has to
  25. provide at least an `gettext` and optoinally a `ngettext` function into the
  26. namespace. Either globally or for each rendering.
  27. Environment Methods
  28. ~~~~~~~~~~~~~~~~~~~
  29. After enabling of the extension the environment provides the following
  30. additional methods:
  31. .. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)
  32. Installs a translation globally for that environment. The tranlations
  33. object provided must implement at least `ugettext` and `ungettext`.
  34. The `gettext.NullTranslations` and `gettext.GNUTranslations` classes
  35. as well as `Babel`_\s `Translations` class are supported.
  36. .. versionchanged:: 2.5 newstyle gettext added
  37. .. method:: jinja2.Environment.install_null_translations(newstyle=False)
  38. Install dummy gettext functions. This is useful if you want to prepare
  39. the application for internationalization but don't want to implement the
  40. full internationalization system yet.
  41. .. versionchanged:: 2.5 newstyle gettext added
  42. .. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False)
  43. Installs the given `gettext` and `ngettext` callables into the
  44. environment as globals. They are supposed to behave exactly like the
  45. standard library's :func:`gettext.ugettext` and
  46. :func:`gettext.ungettext` functions.
  47. If `newstyle` is activated, the callables are wrapped to work like
  48. newstyle callables. See :ref:`newstyle-gettext` for more information.
  49. .. versionadded:: 2.5
  50. .. method:: jinja2.Environment.uninstall_gettext_translations()
  51. Uninstall the translations again.
  52. .. method:: jinja2.Environment.extract_translations(source)
  53. Extract localizable strings from the given template node or source.
  54. For every string found this function yields a ``(lineno, function,
  55. message)`` tuple, where:
  56. * `lineno` is the number of the line on which the string was found,
  57. * `function` is the name of the `gettext` function used (if the
  58. string was extracted from embedded Python code), and
  59. * `message` is the string itself (a `unicode` object, or a tuple
  60. of `unicode` objects for functions with multiple string arguments).
  61. If `Babel`_ is installed :ref:`the babel integration <babel-integration>`
  62. can be used to extract strings for babel.
  63. For a web application that is available in multiple languages but gives all
  64. the users the same language (for example a multilingual forum software
  65. installed for a French community) may load the translations once and add the
  66. translation methods to the environment at environment generation time::
  67. translations = get_gettext_translations()
  68. env = Environment(extensions=['jinja2.ext.i18n'])
  69. env.install_gettext_translations(translations)
  70. The `get_gettext_translations` function would return the translator for the
  71. current configuration. (For example by using `gettext.find`)
  72. The usage of the `i18n` extension for template designers is covered as part
  73. :ref:`of the template documentation <i18n-in-templates>`.
  74. .. _gettext: http://docs.python.org/dev/library/gettext
  75. .. _Babel: http://babel.edgewall.org/
  76. .. _newstyle-gettext:
  77. Newstyle Gettext
  78. ~~~~~~~~~~~~~~~~
  79. .. versionadded:: 2.5
  80. Starting with version 2.5 you can use newstyle gettext calls. These are
  81. inspired by trac's internal gettext functions and are fully supported by
  82. the babel extraction tool. They might not work as expected by other
  83. extraction tools in case you are not using Babel's.
  84. What's the big difference between standard and newstyle gettext calls? In
  85. general they are less to type and less error prone. Also if they are used
  86. in an autoescaping environment they better support automatic escaping.
  87. Here some common differences between old and new calls:
  88. standard gettext:
  89. .. sourcecode:: html+jinja
  90. {{ gettext('Hello World!') }}
  91. {{ gettext('Hello %(name)s!')|format(name='World') }}
  92. {{ ngettext('%(num)d apple', '%(num)d apples', apples|count)|format(
  93. num=apples|count
  94. )}}
  95. newstyle gettext looks like this instead:
  96. .. sourcecode:: html+jinja
  97. {{ gettext('Hello World!') }}
  98. {{ gettext('Hello %(name)s!', name='World') }}
  99. {{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }}
  100. The advantages of newstyle gettext is that you have less to type and that
  101. named placeholders become mandatory. The latter sounds like a
  102. disadvantage but solves a lot of troubles translators are often facing
  103. when they are unable to switch the positions of two placeholder. With
  104. newstyle gettext, all format strings look the same.
  105. Furthermore with newstyle gettext, string formatting is also used if no
  106. placeholders are used which makes all strings behave exactly the same.
  107. Last but not least are newstyle gettext calls able to properly mark
  108. strings for autoescaping which solves lots of escaping related issues many
  109. templates are experiencing over time when using autoescaping.
  110. Expression Statement
  111. --------------------
  112. **Import name:** `jinja2.ext.do`
  113. The "do" aka expression-statement extension adds a simple `do` tag to the
  114. template engine that works like a variable expression but ignores the
  115. return value.
  116. .. _loopcontrols-extension:
  117. Loop Controls
  118. -------------
  119. **Import name:** `jinja2.ext.loopcontrols`
  120. This extension adds support for `break` and `continue` in loops. After
  121. enabling Jinja2 provides those two keywords which work exactly like in
  122. Python.
  123. .. _with-extension:
  124. With Statement
  125. --------------
  126. **Import name:** `jinja2.ext.with_`
  127. .. versionadded:: 2.3
  128. This extension adds support for the with keyword. Using this keyword it
  129. is possible to enforce a nested scope in a template. Variables can be
  130. declared directly in the opening block of the with statement or using a
  131. standard `set` statement directly within.
  132. .. _autoescape-extension:
  133. Autoescape Extension
  134. --------------------
  135. **Import name:** `jinja2.ext.autoescape`
  136. .. versionadded:: 2.4
  137. The autoescape extension allows you to toggle the autoescape feature from
  138. within the template. If the environment's :attr:`~Environment.autoescape`
  139. setting is set to `False` it can be activated, if it's `True` it can be
  140. deactivated. The setting overriding is scoped.
  141. .. _writing-extensions:
  142. Writing Extensions
  143. ------------------
  144. .. module:: jinja2.ext
  145. By writing extensions you can add custom tags to Jinja2. This is a non trival
  146. task and usually not needed as the default tags and expressions cover all
  147. common use cases. The i18n extension is a good example of why extensions are
  148. useful, another one would be fragment caching.
  149. When writing extensions you have to keep in mind that you are working with the
  150. Jinja2 template compiler which does not validate the node tree you are possing
  151. to it. If the AST is malformed you will get all kinds of compiler or runtime
  152. errors that are horrible to debug. Always make sure you are using the nodes
  153. you create correctly. The API documentation below shows which nodes exist and
  154. how to use them.
  155. Example Extension
  156. ~~~~~~~~~~~~~~~~~
  157. The following example implements a `cache` tag for Jinja2 by using the
  158. `Werkzeug`_ caching contrib module:
  159. .. literalinclude:: cache_extension.py
  160. :language: python
  161. And here is how you use it in an environment::
  162. from jinja2 import Environment
  163. from werkzeug.contrib.cache import SimpleCache
  164. env = Environment(extensions=[FragmentCacheExtension])
  165. env.fragment_cache = SimpleCache()
  166. Inside the template it's then possible to mark blocks as cacheable. The
  167. following example caches a sidebar for 300 seconds:
  168. .. sourcecode:: html+jinja
  169. {% cache 'sidebar', 300 %}
  170. <div class="sidebar">
  171. ...
  172. </div>
  173. {% endcache %}
  174. .. _Werkzeug: http://werkzeug.pocoo.org/
  175. Extension API
  176. ~~~~~~~~~~~~~
  177. Extensions always have to extend the :class:`jinja2.ext.Extension` class:
  178. .. autoclass:: Extension
  179. :members: preprocess, filter_stream, parse, attr, call_method
  180. .. attribute:: identifier
  181. The identifier of the extension. This is always the true import name
  182. of the extension class and must not be changed.
  183. .. attribute:: tags
  184. If the extension implements custom tags this is a set of tag names
  185. the extension is listening for.
  186. Parser API
  187. ~~~~~~~~~~
  188. The parser passed to :meth:`Extension.parse` provides ways to parse
  189. expressions of different types. The following methods may be used by
  190. extensions:
  191. .. autoclass:: jinja2.parser.Parser
  192. :members: parse_expression, parse_tuple, parse_assign_target,
  193. parse_statements, free_identifier, fail
  194. .. attribute:: filename
  195. The filename of the template the parser processes. This is **not**
  196. the load name of the template. For the load name see :attr:`name`.
  197. For templates that were not loaded form the file system this is
  198. `None`.
  199. .. attribute:: name
  200. The load name of the template.
  201. .. attribute:: stream
  202. The current :class:`~jinja2.lexer.TokenStream`
  203. .. autoclass:: jinja2.lexer.TokenStream
  204. :members: push, look, eos, skip, next, next_if, skip_if, expect
  205. .. attribute:: current
  206. The current :class:`~jinja2.lexer.Token`.
  207. .. autoclass:: jinja2.lexer.Token
  208. :members: test, test_any
  209. .. attribute:: lineno
  210. The line number of the token
  211. .. attribute:: type
  212. The type of the token. This string is interned so you may compare
  213. it with arbitrary strings using the `is` operator.
  214. .. attribute:: value
  215. The value of the token.
  216. There is also a utility function in the lexer module that can count newline
  217. characters in strings:
  218. .. autofunction:: jinja2.lexer.count_newlines
  219. AST
  220. ~~~
  221. The AST (Abstract Syntax Tree) is used to represent a template after parsing.
  222. It's build of nodes that the compiler then converts into executable Python
  223. code objects. Extensions that provide custom statements can return nodes to
  224. execute custom Python code.
  225. The list below describes all nodes that are currently available. The AST may
  226. change between Jinja2 versions but will stay backwards compatible.
  227. For more information have a look at the repr of :meth:`jinja2.Environment.parse`.
  228. .. module:: jinja2.nodes
  229. .. jinjanodes::
  230. .. autoexception:: Impossible