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