blob: d9102ecc1b636be679cfbae9a3b59a50d6bd59ab [file] [log] [blame]
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +02001Template Designer Documentation
2===============================
3
Armin Ronacherd84ec462008-04-29 13:43:16 +02004.. highlight:: html+jinja
5
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +02006This document describes the syntax and semantics of the template engine and
7will be most useful as reference to those creating Jinja templates. As the
Wes Turnerd40e9ba2014-12-11 05:24:53 -06008template engine is very flexible, the configuration from the application can
Markus Unterwaditzer459b9082015-03-11 20:56:40 +01009be slightly different from the code presented here in terms of delimiters and
10behavior of undefined values.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020011
12
13Synopsis
14--------
15
Wes Turnerd40e9ba2014-12-11 05:24:53 -060016A Jinja template is simply a text file. Jinja can generate any text-based
Markus Unterwaditzer7ecfbe82015-03-11 20:58:42 +010017format (HTML, XML, CSV, LaTeX, etc.). A Jinja template doesn't need to have a
18specific extension: ``.html``, ``.xml``, or any other extension is just fine.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020019
Markus Unterwaditzer0ce1bca2015-03-11 21:12:47 +010020A template contains **variables** and/or **expressions**, which get replaced
21with values when a template is *rendered*; and **tags**, which control the
22logic of the template. The template syntax is heavily inspired by Django and
23Python.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020024
Markus Unterwaditzer0ce1bca2015-03-11 21:12:47 +010025Below is a minimal template that illustrates a few basics using the default
26Jinja configuration. We will cover the details later in this document::
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020027
Evan Sondereggerb8230a72015-01-07 20:01:40 -050028 <!DOCTYPE html>
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020029 <html lang="en">
30 <head>
31 <title>My Webpage</title>
32 </head>
33 <body>
34 <ul id="navigation">
35 {% for item in navigation %}
36 <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
37 {% endfor %}
38 </ul>
39
40 <h1>My Webpage</h1>
41 {{ a_variable }}
Wes Turnerd40e9ba2014-12-11 05:24:53 -060042
43 {# a comment #}
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020044 </body>
45 </html>
46
Markus Unterwaditzer0ce1bca2015-03-11 21:12:47 +010047The following example shows the default configuration settings. An application
48developer can change the syntax configuration from ``{% foo %}`` to ``<% foo
49%>``, or something similar.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020050
Wes Turnerd40e9ba2014-12-11 05:24:53 -060051There are a few kinds of delimiters. The default Jinja delimiters are
52configured as follows:
53
Markus Unterwaditzer0ce1bca2015-03-11 21:12:47 +010054* ``{% ... %}`` for :ref:`Statements <list-of-control-structures>`
55* ``{{ ... }}`` for :ref:`Expressions` to print to the template output
56* ``{# ... #}`` for :ref:`Comments` not included in the template output
57* ``# ... ##`` for :ref:`Line Statements <line-statements>`
Wes Turnerd40e9ba2014-12-11 05:24:53 -060058
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020059
Armin Ronacher709f6e52008-04-28 18:18:16 +020060.. _variables:
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020061
62Variables
63---------
64
Wes Turnerd40e9ba2014-12-11 05:24:53 -060065Template variables are defined by the context dictionary passed to the
66template.
67
Thomas Ballingerf30ab122013-10-27 18:53:06 -040068You can mess around with the variables in templates provided they are passed in
69by the application. Variables may have attributes or elements on them you can
70access too. What attributes a variable has depends heavily on the application
71providing that variable.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020072
Wes Turnerd40e9ba2014-12-11 05:24:53 -060073You can use a dot (``.``) to access attributes of a variable in addition
74to the standard Python ``__getitem__`` "subscript" syntax (``[]``).
75
76The following lines do the same thing::
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020077
78 {{ foo.bar }}
79 {{ foo['bar'] }}
80
Markus Unterwaditzer0ce1bca2015-03-11 21:12:47 +010081It's important to know that the outer double-curly braces are *not* part of the
82variable, but the print statement. If you access variables inside tags don't
83put the braces around them.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020084
Wes Turnerd40e9ba2014-12-11 05:24:53 -060085If a variable or attribute does not exist, you will get back an undefined
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020086value. What you can do with that kind of value depends on the application
Markus Unterwaditzer0ce1bca2015-03-11 21:12:47 +010087configuration: the default behavior is to evaluate to an empty string if
88printed or iterated over, and to fail for every other operation.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +020089
Armin Ronacherb9388772008-06-25 20:43:18 +020090.. _notes-on-subscriptions:
Armin Ronacher6dc6f292008-06-12 08:50:07 +020091
92.. admonition:: Implementation
93
Wes Turnerd40e9ba2014-12-11 05:24:53 -060094 For the sake of convenience, ``foo.bar`` in Jinja2 does the following
Markus Unterwaditzer0ce1bca2015-03-11 21:12:47 +010095 things on the Python layer:
Armin Ronacher6dc6f292008-06-12 08:50:07 +020096
Wes Turnerd40e9ba2014-12-11 05:24:53 -060097 - check for an attribute called `bar` on `foo`
98 (``getattr(foo, 'bar')``)
99 - if there is not, check for an item ``'bar'`` in `foo`
100 (``foo.__getitem__('bar')``)
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200101 - if there is not, return an undefined object.
102
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600103 ``foo['bar']`` works mostly the same with a small difference in sequence:
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200104
Markus Unterwaditzer0ce1bca2015-03-11 21:12:47 +0100105 - check for an item ``'bar'`` in `foo`.
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600106 (``foo.__getitem__('bar')``)
107 - if there is not, check for an attribute called `bar` on `foo`.
108 (``getattr(foo, 'bar')``)
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200109 - if there is not, return an undefined object.
110
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600111 This is important if an object has an item and attribute with the same
112 name. Additionally, the :func:`attr` filter only looks up attributes.
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200113
Armin Ronacher709f6e52008-04-28 18:18:16 +0200114.. _filters:
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200115
116Filters
117-------
118
Wieland Hoffmann06147472011-07-07 12:09:21 -0700119Variables can be modified by **filters**. Filters are separated from the
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200120variable by a pipe symbol (``|``) and may have optional arguments in
121parentheses. Multiple filters can be chained. The output of one filter is
122applied to the next.
123
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600124For example, ``{{ name|striptags|title }}`` will remove all HTML Tags from
125variable `name` and title-case the output (``title(striptags(name))``).
126
Markus Unterwaditzer0ce1bca2015-03-11 21:12:47 +0100127Filters that accept arguments have parentheses around the arguments, just like
128a function call. For example: ``{{ listx|join(', ') }}`` will join a list with
129commas (``str.join(', ', listx)``).
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200130
Armin Ronacher157531b2008-04-28 16:14:03 +0200131The :ref:`builtin-filters` below describes all the builtin filters.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200132
Armin Ronacher709f6e52008-04-28 18:18:16 +0200133.. _tests:
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200134
135Tests
136-----
137
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600138Beside filters, there are also so-called "tests" available. Tests can be used
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200139to test a variable against a common expression. To test a variable or
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600140expression, you add `is` plus the name of the test after the variable. For
141example, to find out if a variable is defined, you can do ``name is defined``,
142which will then return true or false depending on whether `name` is defined
143in the current template context.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200144
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600145Tests can accept arguments, too. If the test only takes one argument, you can
146leave out the parentheses. For example, the following two
147expressions do the same thing::
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200148
149 {% if loop.index is divisibleby 3 %}
150 {% if loop.index is divisibleby(3) %}
151
Lukas Meuserad48a2e2008-05-01 18:19:57 +0200152The :ref:`builtin-tests` below describes all the builtin tests.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200153
154
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600155.. _comments:
156
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200157Comments
158--------
159
160To comment-out part of a line in a template, use the comment syntax which is
161by default set to ``{# ... #}``. This is useful to comment out parts of the
162template for debugging or to add information for other template designers or
Armin Ronacherd84ec462008-04-29 13:43:16 +0200163yourself::
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200164
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600165 {# note: commented-out template because we no longer use this
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200166 {% for user in users %}
167 ...
168 {% endfor %}
169 #}
170
Armin Ronacherf35e2812008-05-06 16:04:10 +0200171
172Whitespace Control
173------------------
174
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600175In the default configuration:
176
177* a single trailing newline is stripped if present
Markus Unterwaditzer0ce1bca2015-03-11 21:12:47 +0100178* other whitespace (spaces, tabs, newlines etc.) is returned unchanged
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600179
180If an application configures Jinja to `trim_blocks`, the first newline after a
Kristi Tsukida214bb362012-07-10 18:13:52 -0700181template tag is removed automatically (like in PHP). The `lstrip_blocks`
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600182option can also be set to strip tabs and spaces from the beginning of a
Kristi Tsukida214bb362012-07-10 18:13:52 -0700183line to the start of a block. (Nothing will be stripped if there are
184other characters before the start of the block.)
Armin Ronacherf35e2812008-05-06 16:04:10 +0200185
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600186With both `trim_blocks` and `lstrip_blocks` enabled, you can put block tags
Kristi Tsukida214bb362012-07-10 18:13:52 -0700187on their own lines, and the entire block line will be removed when
188rendered, preserving the whitespace of the contents. For example,
189without the `trim_blocks` and `lstrip_blocks` options, this template::
190
191 <div>
192 {% if True %}
193 yay
194 {% endif %}
195 </div>
196
197gets rendered with blank lines inside the div::
198
199 <div>
200
201 yay
202
203 </div>
204
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600205But with both `trim_blocks` and `lstrip_blocks` enabled, the template block
206lines are removed and other whitespace is preserved::
Kristi Tsukida214bb362012-07-10 18:13:52 -0700207
208 <div>
209 yay
210 </div>
211
Kristi Tsukidae4a74f92012-07-12 13:44:54 -0700212You can manually disable the `lstrip_blocks` behavior by putting a
213plus sign (``+``) at the start of a block::
214
215 <div>
216 {%+ if something %}yay{% endif %}
217 </div>
218
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600219You can also strip whitespace in templates by hand. If you add a minus
220sign (``-``) to the start or end of a block (e.g. a :ref:`for-loop` tag), a
221comment, or a variable expression, the whitespaces before or after
222that block will be removed::
Armin Ronacherf35e2812008-05-06 16:04:10 +0200223
224 {% for item in seq -%}
225 {{ item }}
226 {%- endfor %}
Andy McKay20044492011-06-30 14:40:05 -0700227
Armin Ronacherf35e2812008-05-06 16:04:10 +0200228This will yield all elements without whitespace between them. If `seq` was
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600229a list of numbers from ``1`` to ``9``, the output would be ``123456789``.
Armin Ronacherf35e2812008-05-06 16:04:10 +0200230
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600231If :ref:`line-statements` are enabled, they strip leading whitespace
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200232automatically up to the beginning of the line.
Armin Ronacherf35e2812008-05-06 16:04:10 +0200233
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600234By default, Jinja2 also removes trailing newlines. To keep single
235trailing newlines, configure Jinja to `keep_trailing_newline`.
Armin Ronachera65f1eb2013-05-19 11:18:19 +0100236
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200237.. admonition:: Note
238
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600239 You must not add whitespace between the tag and the minus sign.
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200240
241 **valid**::
Armin Ronacher61a5a242008-05-26 12:07:44 +0200242
Armin Ronacherf35e2812008-05-06 16:04:10 +0200243 {%- if foo -%}...{% endif %}
244
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200245 **invalid**::
Armin Ronacherf35e2812008-05-06 16:04:10 +0200246
247 {% - if foo - %}...{% endif %}
248
Armin Ronacherf35e2812008-05-06 16:04:10 +0200249
250Escaping
251--------
252
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600253It is sometimes desirable -- even necessary -- to have Jinja ignore parts
254it would otherwise handle as variables or blocks. For example, if, with
255the default syntax, you want to use ``{{`` as a raw string in a template and
256not start a variable, you have to use a trick.
Armin Ronacherf35e2812008-05-06 16:04:10 +0200257
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600258The easiest way to output a literal variable delimiter (``{{``) is by using a
Armin Ronacherf35e2812008-05-06 16:04:10 +0200259variable expression::
260
261 {{ '{{' }}
262
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600263For bigger sections, it makes sense to mark a block `raw`. For example, to
264include example Jinja syntax in a template, you can use this snippet::
Armin Ronacherf35e2812008-05-06 16:04:10 +0200265
266 {% raw %}
267 <ul>
268 {% for item in seq %}
269 <li>{{ item }}</li>
270 {% endfor %}
271 </ul>
272 {% endraw %}
273
274
275.. _line-statements:
276
277Line Statements
278---------------
279
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600280If line statements are enabled by the application, it's possible to mark a
281line as a statement. For example, if the line statement prefix is configured
282to ``#``, the following two examples are equivalent::
Armin Ronacherf35e2812008-05-06 16:04:10 +0200283
284 <ul>
285 # for item in seq
286 <li>{{ item }}</li>
287 # endfor
288 </ul>
289
290 <ul>
291 {% for item in seq %}
292 <li>{{ item }}</li>
293 {% endfor %}
294 </ul>
295
296The line statement prefix can appear anywhere on the line as long as no text
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600297precedes it. For better readability, statements that start a block (such as
Armin Ronacherf35e2812008-05-06 16:04:10 +0200298`for`, `if`, `elif` etc.) may end with a colon::
299
300 # for item in seq:
301 ...
Georg Brandlac61b242008-05-11 12:30:19 +0200302 # endfor
Armin Ronacherf35e2812008-05-06 16:04:10 +0200303
304
Armin Ronacher3ef20432008-06-09 18:27:19 +0200305.. admonition:: Note
306
307 Line statements can span multiple lines if there are open parentheses,
308 braces or brackets::
309
310 <ul>
311 # for href, caption in [('index.html', 'Index'),
312 ('about.html', 'About')]:
313 <li><a href="{{ href }}">{{ caption }}</a></li>
314 # endfor
315 </ul>
316
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600317Since Jinja 2.2, line-based comments are available as well. For example, if
318the line-comment prefix is configured to be ``##``, everything from ``##`` to
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200319the end of the line is ignored (excluding the newline sign)::
320
321 # for item in seq:
322 <li>{{ item }}</li> ## this comment is ignored
323 # endfor
324
Armin Ronacher3ef20432008-06-09 18:27:19 +0200325
Armin Ronacherd84ec462008-04-29 13:43:16 +0200326.. _template-inheritance:
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200327
328Template Inheritance
329--------------------
330
331The most powerful part of Jinja is template inheritance. Template inheritance
332allows you to build a base "skeleton" template that contains all the common
333elements of your site and defines **blocks** that child templates can override.
334
335Sounds complicated but is very basic. It's easiest to understand it by starting
336with an example.
337
338
339Base Template
340~~~~~~~~~~~~~
341
342This template, which we'll call ``base.html``, defines a simple HTML skeleton
343document that you might use for a simple two-column page. It's the job of
Armin Ronacherd84ec462008-04-29 13:43:16 +0200344"child" templates to fill the empty blocks with content::
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200345
Evan Sondereggerb8230a72015-01-07 20:01:40 -0500346 <!DOCTYPE html>
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200347 <html lang="en">
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200348 <head>
349 {% block head %}
350 <link rel="stylesheet" href="style.css" />
351 <title>{% block title %}{% endblock %} - My Webpage</title>
352 {% endblock %}
353 </head>
354 <body>
355 <div id="content">{% block content %}{% endblock %}</div>
356 <div id="footer">
357 {% block footer %}
358 &copy; Copyright 2008 by <a href="http://domain.invalid/">you</a>.
359 {% endblock %}
360 </div>
361 </body>
Evan Sondereggerb8230a72015-01-07 20:01:40 -0500362 </html>
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200363
364In this example, the ``{% block %}`` tags define four blocks that child templates
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600365can fill in. All the `block` tag does is tell the template engine that a
366child template may override those placeholders in the template.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200367
368Child Template
369~~~~~~~~~~~~~~
370
Armin Ronacherd84ec462008-04-29 13:43:16 +0200371A child template might look like this::
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200372
373 {% extends "base.html" %}
374 {% block title %}Index{% endblock %}
375 {% block head %}
376 {{ super() }}
377 <style type="text/css">
378 .important { color: #336699; }
379 </style>
380 {% endblock %}
381 {% block content %}
382 <h1>Index</h1>
383 <p class="important">
Carlos Eduardo Riveracf845c92015-01-18 20:22:34 -0600384 Welcome to my awesome homepage.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200385 </p>
386 {% endblock %}
387
388The ``{% extends %}`` tag is the key here. It tells the template engine that
389this template "extends" another template. When the template system evaluates
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600390this template, it first locates the parent. The extends tag should be the
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200391first tag in the template. Everything before it is printed out normally and
Armin Ronacherfdf95302008-05-11 22:20:51 +0200392may cause confusion. For details about this behavior and how to take
393advantage of it, see :ref:`null-master-fallback`.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200394
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600395The filename of the template depends on the template loader. For example, the
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200396:class:`FileSystemLoader` allows you to access other templates by giving the
Christoph Zwerschkea21f2ed2011-10-23 18:23:58 +0200397filename. You can access templates in subdirectories with a slash::
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200398
399 {% extends "layout/default.html" %}
400
401But this behavior can depend on the application embedding Jinja. Note that
402since the child template doesn't define the ``footer`` block, the value from
403the parent template is used instead.
404
405You can't define multiple ``{% block %}`` tags with the same name in the
406same template. This limitation exists because a block tag works in "both"
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600407directions. That is, a block tag doesn't just provide a placeholder to fill
408- it also defines the content that fills the placeholder in the *parent*.
409If there were two similarly-named ``{% block %}`` tags in a template,
410that template's parent wouldn't know which one of the blocks' content to use.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200411
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600412If you want to print a block multiple times, you can, however, use the special
Armin Ronacherd84ec462008-04-29 13:43:16 +0200413`self` variable and call the block with that name::
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200414
415 <title>{% block title %}{% endblock %}</title>
416 <h1>{{ self.title() }}</h1>
417 {% block body %}{% endblock %}
418
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200419
420Super Blocks
421~~~~~~~~~~~~
422
423It's possible to render the contents of the parent block by calling `super`.
Armin Ronacherd84ec462008-04-29 13:43:16 +0200424This gives back the results of the parent block::
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200425
426 {% block sidebar %}
427 <h3>Table Of Contents</h3>
428 ...
429 {{ super() }}
430 {% endblock %}
431
432
Armin Ronacherfd310492008-05-25 00:16:51 +0200433Named Block End-Tags
434~~~~~~~~~~~~~~~~~~~~
435
436Jinja2 allows you to put the name of the block after the end tag for better
437readability::
438
439 {% block sidebar %}
440 {% block inner_sidebar %}
441 ...
442 {% endblock inner_sidebar %}
443 {% endblock sidebar %}
444
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600445However, the name after the `endblock` word must match the block name.
Armin Ronacherfd310492008-05-25 00:16:51 +0200446
447
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100448Block Nesting and Scope
449~~~~~~~~~~~~~~~~~~~~~~~
450
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600451Blocks can be nested for more complex layouts. However, per default blocks
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100452may not access variables from outer scopes::
453
454 {% for item in seq %}
455 <li>{% block loop_item %}{{ item }}{% endblock %}</li>
456 {% endfor %}
457
458This example would output empty ``<li>`` items because `item` is unavailable
459inside the block. The reason for this is that if the block is replaced by
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600460a child template, a variable would appear that was not defined in the block or
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100461passed to the context.
462
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600463Starting with Jinja 2.2, you can explicitly specify that variables are
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100464available in a block by setting the block to "scoped" by adding the `scoped`
465modifier to a block declaration::
466
467 {% for item in seq %}
468 <li>{% block loop_item scoped %}{{ item }}{% endblock %}</li>
469 {% endfor %}
470
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600471When overriding a block, the `scoped` modifier does not have to be provided.
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100472
473
Armin Ronacher9165d3e2010-02-16 17:35:59 +0100474Template Objects
475~~~~~~~~~~~~~~~~
476
477.. versionchanged:: 2.4
478
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600479If a template object was passed in the template context, you can
Armin Ronacher9165d3e2010-02-16 17:35:59 +0100480extend from that object as well. Assuming the calling code passes
481a layout template as `layout_template` to the environment, this
482code works::
483
484 {% extends layout_template %}
485
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600486Previously, the `layout_template` variable had to be a string with
Armin Ronacher9165d3e2010-02-16 17:35:59 +0100487the layout template's filename for this to work.
488
489
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200490HTML Escaping
491-------------
492
493When generating HTML from templates, there's always a risk that a variable will
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600494include characters that affect the resulting HTML. There are two approaches:
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200495
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600496a. manually escaping each variable; or
497b. automatically escaping everything by default.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200498
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600499Jinja supports both. What is used depends on the application configuration.
500The default configuration is no automatic escaping; for various reasons:
501
502- Escaping everything except for safe values will also mean that Jinja is
503 escaping variables known to not include HTML (e.g. numbers, booleans)
504 which can be a huge performance hit.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200505
506- The information about the safety of a variable is very fragile. It could
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600507 happen that by coercing safe and unsafe values, the return value is
508 double-escaped HTML.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200509
510Working with Manual Escaping
Armin Ronacher157531b2008-04-28 16:14:03 +0200511~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200512
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600513If manual escaping is enabled, it's **your** responsibility to escape
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200514variables if needed. What to escape? If you have a variable that *may*
515include any of the following chars (``>``, ``<``, ``&``, or ``"``) you
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600516**SHOULD** escape it unless the variable contains well-formed and trusted
517HTML. Escaping works by piping the variable through the ``|e`` filter::
518
519 {{ user.username|e }}
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200520
521Working with Automatic Escaping
Armin Ronacher157531b2008-04-28 16:14:03 +0200522~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200523
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600524When automatic escaping is enabled, everything is escaped by default except
525for values explicitly marked as safe. Variables and expressions
526can be marked as safe either in:
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200527
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600528a. the context dictionary by the application with `MarkupSafe.Markup`, or
529b. the template, with the `|safe` filter
530
Markus Unterwaditzer0ce1bca2015-03-11 21:12:47 +0100531The main problem with this approach is that Python itself doesn't have the
532concept of tainted values; so whether a value is safe or unsafe can get lost.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200533
Markus Unterwaditzer0ce1bca2015-03-11 21:12:47 +0100534If a value is not marked safe, auto-escaping will take place; which means that
535you could end up with double-escaped contents. Double-escaping is easy to
536avoid, however: just rely on the tools Jinja2 provides and *don't use builtin
537Python constructs such as str.format or the string modulo operator (%)*.
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600538
Markus Unterwaditzer0ce1bca2015-03-11 21:12:47 +0100539Jinja2 functions (macros, `super`, `self.BLOCKNAME`) always return template
540data that is marked as safe.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200541
542String literals in templates with automatic escaping are considered unsafe
Markus Unterwaditzer0ce1bca2015-03-11 21:12:47 +0100543because native Python strings (``str``, ``unicode``, ``basestring``) are not
544`MarkupSafe.Markup` strings with an ``__html__`` attribute.
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200545
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600546.. _list-of-control-structures:
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +0200547
Armin Ronacher157531b2008-04-28 16:14:03 +0200548List of Control Structures
549--------------------------
550
551A control structure refers to all those things that control the flow of a
552program - conditionals (i.e. if/elif/else), for-loops, as well as things like
Markus Unterwaditzer0ce1bca2015-03-11 21:12:47 +0100553macros and blocks. With the default syntax, control structures appear inside
554``{% ... %}`` blocks.
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600555
556.. _for-loop:
Armin Ronacher157531b2008-04-28 16:14:03 +0200557
Armin Ronacherd84ec462008-04-29 13:43:16 +0200558For
559~~~
Armin Ronacher157531b2008-04-28 16:14:03 +0200560
Lukas Meuserad48a2e2008-05-01 18:19:57 +0200561Loop over each item in a sequence. For example, to display a list of users
Armin Ronacherd84ec462008-04-29 13:43:16 +0200562provided in a variable called `users`::
Armin Ronacher157531b2008-04-28 16:14:03 +0200563
564 <h1>Members</h1>
565 <ul>
566 {% for user in users %}
567 <li>{{ user.username|e }}</li>
568 {% endfor %}
569 </ul>
570
Armin Ronacher898975d2011-10-06 10:09:31 -0400571As variables in templates retain their object properties, it is possible to
572iterate over containers like `dict`::
573
574 <dl>
575 {% for key, value in my_dict.iteritems() %}
576 <dt>{{ key|e }}</dt>
577 <dd>{{ value|e }}</dd>
578 {% endfor %}
579 </dl>
580
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600581Note, however, that **Python dicts are not ordered**; so you might want to
Markus Unterwaditzer0ce1bca2015-03-11 21:12:47 +0100582either pass a sorted ``list`` of ``tuple`` s -- or a
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600583``collections.OrderedDict`` -- to the template, or use the `dictsort` filter.
Armin Ronacher898975d2011-10-06 10:09:31 -0400584
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600585Inside of a for-loop block, you can access some special variables:
Armin Ronacher157531b2008-04-28 16:14:03 +0200586
587+-----------------------+---------------------------------------------------+
Armin Ronacher709f6e52008-04-28 18:18:16 +0200588| Variable | Description |
589+=======================+===================================================+
Armin Ronacher157531b2008-04-28 16:14:03 +0200590| `loop.index` | The current iteration of the loop. (1 indexed) |
591+-----------------------+---------------------------------------------------+
592| `loop.index0` | The current iteration of the loop. (0 indexed) |
593+-----------------------+---------------------------------------------------+
594| `loop.revindex` | The number of iterations from the end of the loop |
595| | (1 indexed) |
596+-----------------------+---------------------------------------------------+
597| `loop.revindex0` | The number of iterations from the end of the loop |
598| | (0 indexed) |
599+-----------------------+---------------------------------------------------+
600| `loop.first` | True if first iteration. |
601+-----------------------+---------------------------------------------------+
602| `loop.last` | True if last iteration. |
603+-----------------------+---------------------------------------------------+
604| `loop.length` | The number of items in the sequence. |
605+-----------------------+---------------------------------------------------+
606| `loop.cycle` | A helper function to cycle between a list of |
607| | sequences. See the explanation below. |
608+-----------------------+---------------------------------------------------+
Armin Ronacher568352e2013-05-20 09:26:57 +0100609| `loop.depth` | Indicates how deep in deep in a recursive loop |
610| | the rendering currently is. Starts at level 1 |
611+-----------------------+---------------------------------------------------+
Armin Ronacherda94a8b2013-05-20 14:06:59 +0100612| `loop.depth0` | Indicates how deep in deep in a recursive loop |
Armin Ronacher568352e2013-05-20 09:26:57 +0100613| | the rendering currently is. Starts at level 0 |
614+-----------------------+---------------------------------------------------+
Armin Ronacher157531b2008-04-28 16:14:03 +0200615
Lukas Meuserad48a2e2008-05-01 18:19:57 +0200616Within a for-loop, it's possible to cycle among a list of strings/variables
Armin Ronacherd84ec462008-04-29 13:43:16 +0200617each time through the loop by using the special `loop.cycle` helper::
Armin Ronacher157531b2008-04-28 16:14:03 +0200618
619 {% for row in rows %}
620 <li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>
621 {% endfor %}
622
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600623Since Jinja 2.1, an extra `cycle` helper exists that allows loop-unbound
624cycling. For more information, have a look at the :ref:`builtin-globals`.
Armin Ronacherccae0552008-10-05 23:08:58 +0200625
Armin Ronacher709f6e52008-04-28 18:18:16 +0200626.. _loop-filtering:
627
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600628Unlike in Python, it's not possible to `break` or `continue` in a loop. You
629can, however, filter the sequence during iteration, which allows you to skip
Armin Ronacherd84ec462008-04-29 13:43:16 +0200630items. The following example skips all the users which are hidden::
Armin Ronacher157531b2008-04-28 16:14:03 +0200631
632 {% for user in users if not user.hidden %}
633 <li>{{ user.username|e }}</li>
634 {% endfor %}
635
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600636The advantage is that the special `loop` variable will count correctly; thus
Armin Ronacher157531b2008-04-28 16:14:03 +0200637not counting the users not iterated over.
638
639If no iteration took place because the sequence was empty or the filtering
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600640removed all the items from the sequence, you can render a default block
Armin Ronacherd84ec462008-04-29 13:43:16 +0200641by using `else`::
Armin Ronacher157531b2008-04-28 16:14:03 +0200642
643 <ul>
644 {% for user in users %}
645 <li>{{ user.username|e }}</li>
646 {% else %}
647 <li><em>no users found</em></li>
Armin Ronacher890dac02010-02-06 16:36:52 +0100648 {% endfor %}
Armin Ronacher157531b2008-04-28 16:14:03 +0200649 </ul>
Armin Ronacher709f6e52008-04-28 18:18:16 +0200650
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600651Note that, in Python, `else` blocks are executed whenever the corresponding
652loop **did not** `break`. Since Jinja loops cannot `break` anyway,
Christoph Zwerschke4780c2c2012-03-21 16:56:36 +0100653a slightly different behavior of the `else` keyword was chosen.
654
Armin Ronacher1de4c642008-05-11 23:55:02 +0200655It is also possible to use loops recursively. This is useful if you are
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600656dealing with recursive data such as sitemaps or RDFa.
657To use loops recursively, you basically have to add the `recursive` modifier
658to the loop definition and call the `loop` variable with the new iterable
659where you want to recurse.
Armin Ronacher1de4c642008-05-11 23:55:02 +0200660
661The following example implements a sitemap with recursive loops::
662
663 <ul class="sitemap">
664 {%- for item in sitemap recursive %}
665 <li><a href="{{ item.href|e }}">{{ item.title }}</a>
666 {%- if item.children -%}
667 <ul class="submenu">{{ loop(item.children) }}</ul>
668 {%- endif %}</li>
669 {%- endfor %}
670 </ul>
671
Dimitris Leventeasaa023e42012-11-01 23:21:32 +0100672The `loop` variable always refers to the closest (innermost) loop. If we
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600673have more than one level of loops, we can rebind the variable `loop` by
Dimitris Leventeasaa023e42012-11-01 23:21:32 +0100674writing `{% set outer_loop = loop %}` after the loop that we want to
675use recursively. Then, we can call it using `{{ outer_loop(...) }}`
Armin Ronacher709f6e52008-04-28 18:18:16 +0200676
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600677.. _if:
678
Armin Ronacher709f6e52008-04-28 18:18:16 +0200679If
680~~
681
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600682The `if` statement in Jinja is comparable with the Python if statement.
683In the simplest form, you can use it to test if a variable is defined, not
Armin Ronacherd84ec462008-04-29 13:43:16 +0200684empty or not false::
Armin Ronacher709f6e52008-04-28 18:18:16 +0200685
686 {% if users %}
687 <ul>
688 {% for user in users %}
689 <li>{{ user.username|e }}</li>
690 {% endfor %}
691 </ul>
692 {% endif %}
693
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600694For multiple branches, `elif` and `else` can be used like in Python. You can
695use more complex :ref:`expressions` there, too::
Armin Ronacher709f6e52008-04-28 18:18:16 +0200696
697 {% if kenny.sick %}
698 Kenny is sick.
699 {% elif kenny.dead %}
700 You killed Kenny! You bastard!!!
701 {% else %}
702 Kenny looks okay --- so far
703 {% endif %}
704
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600705If can also be used as an :ref:`inline expression <if-expression>` and for
Armin Ronacher709f6e52008-04-28 18:18:16 +0200706:ref:`loop filtering <loop-filtering>`.
707
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600708.. _macros:
Armin Ronacher709f6e52008-04-28 18:18:16 +0200709
Armin Ronacherd84ec462008-04-29 13:43:16 +0200710Macros
711~~~~~~
712
Lukas Meuserad48a2e2008-05-01 18:19:57 +0200713Macros are comparable with functions in regular programming languages. They
714are useful to put often used idioms into reusable functions to not repeat
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600715yourself ("DRY").
Armin Ronacherd84ec462008-04-29 13:43:16 +0200716
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600717Here's a small example of a macro that renders a form element::
Armin Ronacherd84ec462008-04-29 13:43:16 +0200718
719 {% macro input(name, value='', type='text', size=20) -%}
720 <input type="{{ type }}" name="{{ name }}" value="{{
721 value|e }}" size="{{ size }}">
722 {%- endmacro %}
723
724The macro can then be called like a function in the namespace::
725
726 <p>{{ input('username') }}</p>
727 <p>{{ input('password', type='password') }}</p>
728
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600729If the macro was defined in a different template, you have to
Armin Ronacherd84ec462008-04-29 13:43:16 +0200730:ref:`import <import>` it first.
731
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600732Inside macros, you have access to three special variables:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200733
734`varargs`
Lukas Meuserad48a2e2008-05-01 18:19:57 +0200735 If more positional arguments are passed to the macro than accepted by the
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600736 macro, they end up in the special `varargs` variable as a list of values.
Armin Ronacherd84ec462008-04-29 13:43:16 +0200737
738`kwargs`
739 Like `varargs` but for keyword arguments. All unconsumed keyword
740 arguments are stored in this special variable.
741
742`caller`
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600743 If the macro was called from a :ref:`call<call>` tag, the caller is stored
744 in this variable as a callable macro.
Armin Ronacherd84ec462008-04-29 13:43:16 +0200745
746Macros also expose some of their internal details. The following attributes
747are available on a macro object:
748
749`name`
750 The name of the macro. ``{{ input.name }}`` will print ``input``.
751
752`arguments`
753 A tuple of the names of arguments the macro accepts.
754
755`defaults`
756 A tuple of default values.
757
758`catch_kwargs`
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600759 This is `true` if the macro accepts extra keyword arguments (i.e.: accesses
Armin Ronacherd84ec462008-04-29 13:43:16 +0200760 the special `kwargs` variable).
761
762`catch_varargs`
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600763 This is `true` if the macro accepts extra positional arguments (i.e.:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200764 accesses the special `varargs` variable).
765
766`caller`
767 This is `true` if the macro accesses the special `caller` variable and may
Lukas Meuserad48a2e2008-05-01 18:19:57 +0200768 be called from a :ref:`call<call>` tag.
Armin Ronacherd84ec462008-04-29 13:43:16 +0200769
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600770If a macro name starts with an underscore, it's not exported and can't
Armin Ronacherc347ed02008-09-20 12:04:53 +0200771be imported.
772
Armin Ronacherd84ec462008-04-29 13:43:16 +0200773
774.. _call:
775
776Call
777~~~~
778
779In some cases it can be useful to pass a macro to another macro. For this
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600780purpose, you can use the special `call` block. The following example shows
Armin Ronacherd84ec462008-04-29 13:43:16 +0200781a macro that takes advantage of the call functionality and how it can be
782used::
783
784 {% macro render_dialog(title, class='dialog') -%}
785 <div class="{{ class }}">
786 <h2>{{ title }}</h2>
787 <div class="contents">
788 {{ caller() }}
789 </div>
790 </div>
791 {%- endmacro %}
792
793 {% call render_dialog('Hello World') %}
794 This is a simple dialog rendered by using a macro and
795 a call block.
796 {% endcall %}
797
798It's also possible to pass arguments back to the call block. This makes it
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600799useful as a replacement for loops. Generally speaking, a call block works
800exactly like a macro without a name.
Armin Ronacherd84ec462008-04-29 13:43:16 +0200801
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600802Here's an example of how a call block can be used with arguments::
Armin Ronacherd84ec462008-04-29 13:43:16 +0200803
804 {% macro dump_users(users) -%}
805 <ul>
806 {%- for user in users %}
807 <li><p>{{ user.username|e }}</p>{{ caller(user) }}</li>
808 {%- endfor %}
809 </ul>
810 {%- endmacro %}
811
812 {% call(user) dump_users(list_of_user) %}
813 <dl>
814 <dl>Realname</dl>
815 <dd>{{ user.realname|e }}</dd>
816 <dl>Description</dl>
817 <dd>{{ user.description }}</dd>
818 </dl>
819 {% endcall %}
820
821
Armin Ronacher76f9aa42008-07-12 02:08:29 +0200822Filters
823~~~~~~~
824
825Filter sections allow you to apply regular Jinja2 filters on a block of
826template data. Just wrap the code in the special `filter` section::
827
828 {% filter upper %}
829 This text becomes uppercase
830 {% endfilter %}
831
832
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600833.. _assignments:
834
Armin Ronacherd84ec462008-04-29 13:43:16 +0200835Assignments
836~~~~~~~~~~~
837
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600838Inside code blocks, you can also assign values to variables. Assignments at
Armin Ronacherd84ec462008-04-29 13:43:16 +0200839top level (outside of blocks, macros or loops) are exported from the template
840like top level macros and can be imported by other templates.
841
Armin Ronacher2e30cf52008-05-13 01:05:20 +0200842Assignments use the `set` tag and can have multiple targets::
Armin Ronacherd84ec462008-04-29 13:43:16 +0200843
Armin Ronacher2e30cf52008-05-13 01:05:20 +0200844 {% set navigation = [('index.html', 'Index'), ('about.html', 'About')] %}
845 {% set key, value = call_something() %}
Armin Ronacherd84ec462008-04-29 13:43:16 +0200846
847
Armin Ronacher3d91ae52014-06-07 00:58:38 +0600848Block Assignments
849~~~~~~~~~~~~~~~~~
850
851.. versionadded:: 2.8
852
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600853Starting with Jinja 2.8, it's possible to also use block assignments to
Armin Ronacher3d91ae52014-06-07 00:58:38 +0600854capture the contents of a block into a variable name. This can be useful
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600855in some situations as an alternative for macros. In that case, instead of
856using an equals sign and a value, you just write the variable name and then
Armin Ronacher3d91ae52014-06-07 00:58:38 +0600857everything until ``{% endset %}`` is captured.
858
859Example::
860
861 {% set navigation %}
862 <li><a href="/">Index</a>
863 <li><a href="/downloads">Downloads</a>
864 {% endset %}
865
866The `navigation` variable then contains the navigation HTML source.
867
868
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600869.. _extends:
870
Armin Ronacherd84ec462008-04-29 13:43:16 +0200871Extends
872~~~~~~~
873
Markus Unterwaditzer0ce1bca2015-03-11 21:12:47 +0100874The `extends` tag can be used to extend one template from another. You can
875have multiple `extends` tags in a file, but only one of them may be executed at
876a time.
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600877
878See the section about :ref:`template-inheritance` above.
Armin Ronacherd84ec462008-04-29 13:43:16 +0200879
880
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600881.. _blocks:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200882
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600883Blocks
884~~~~~~
885
886Blocks are used for inheritance and act as both placeholders and replacements
887at the same time. They are documented in detail in the
888:ref:`template-inheritance` section.
Armin Ronacherd84ec462008-04-29 13:43:16 +0200889
890
891Include
892~~~~~~~
893
894The `include` statement is useful to include a template and return the
895rendered contents of that file into the current namespace::
896
897 {% include 'header.html' %}
898 Body
899 {% include 'footer.html' %}
900
Armin Ronacherea847c52008-05-02 20:04:32 +0200901Included templates have access to the variables of the active context by
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600902default. For more details about context behavior of imports and includes,
Armin Ronacherea847c52008-05-02 20:04:32 +0200903see :ref:`import-visibility`.
Armin Ronacherd84ec462008-04-29 13:43:16 +0200904
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600905From Jinja 2.2 onwards, you can mark an include with ``ignore missing``; in
Dmitry Medvinsky200fe172012-09-21 17:15:38 +0400906which case Jinja will ignore the statement if the template to be included
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600907does not exist. When combined with ``with`` or ``without context``, it must
908be placed *before* the context visibility statement. Here are some valid
Armin Ronacher37f58ce2008-12-27 13:10:38 +0100909examples::
910
911 {% include "sidebar.html" ignore missing %}
912 {% include "sidebar.html" ignore missing with context %}
913 {% include "sidebar.html" ignore missing without context %}
914
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100915.. versionadded:: 2.2
916
917You can also provide a list of templates that are checked for existence
918before inclusion. The first template that exists will be included. If
919`ignore missing` is given, it will fall back to rendering nothing if
920none of the templates exist, otherwise it will raise an exception.
921
922Example::
923
924 {% include ['page_detailed.html', 'page.html'] %}
925 {% include ['special_sidebar.html', 'sidebar.html'] ignore missing %}
926
Armin Ronacher9165d3e2010-02-16 17:35:59 +0100927.. versionchanged:: 2.4
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600928 If a template object was passed to the template context, you can
Armin Ronacher9165d3e2010-02-16 17:35:59 +0100929 include that object using `include`.
930
Armin Ronacherd84ec462008-04-29 13:43:16 +0200931.. _import:
932
933Import
934~~~~~~
935
936Jinja2 supports putting often used code into macros. These macros can go into
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600937different templates and get imported from there. This works similarly to the
Armin Ronacherd84ec462008-04-29 13:43:16 +0200938import statements in Python. It's important to know that imports are cached
939and imported templates don't have access to the current template variables,
Christoph Zwerschkea21f2ed2011-10-23 18:23:58 +0200940just the globals by default. For more details about context behavior of
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600941imports and includes, see :ref:`import-visibility`.
Armin Ronacherd84ec462008-04-29 13:43:16 +0200942
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600943There are two ways to import templates. You can import a complete template
Armin Ronacherd84ec462008-04-29 13:43:16 +0200944into a variable or request specific macros / exported variables from it.
945
946Imagine we have a helper module that renders forms (called `forms.html`)::
947
948 {% macro input(name, value='', type='text') -%}
949 <input type="{{ type }}" value="{{ value|e }}" name="{{ name }}">
950 {%- endmacro %}
951
952 {%- macro textarea(name, value='', rows=10, cols=40) -%}
953 <textarea name="{{ name }}" rows="{{ rows }}" cols="{{ cols
954 }}">{{ value|e }}</textarea>
955 {%- endmacro %}
956
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600957The easiest and most flexible way to access a template's variables
958and macros is to import the whole template module into a variable.
959That way, you can access the attributes::
Armin Ronacherd84ec462008-04-29 13:43:16 +0200960
961 {% import 'forms.html' as forms %}
962 <dl>
963 <dt>Username</dt>
964 <dd>{{ forms.input('username') }}</dd>
965 <dt>Password</dt>
966 <dd>{{ forms.input('password', type='password') }}</dd>
967 </dl>
968 <p>{{ forms.textarea('comment') }}</p>
969
970
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600971Alternatively, you can import specific names from a template into the current
Armin Ronacherd84ec462008-04-29 13:43:16 +0200972namespace::
973
974 {% from 'forms.html' import input as input_field, textarea %}
975 <dl>
976 <dt>Username</dt>
977 <dd>{{ input_field('username') }}</dd>
978 <dt>Password</dt>
979 <dd>{{ input_field('password', type='password') }}</dd>
980 </dl>
981 <p>{{ textarea('comment') }}</p>
982
Natan L63bd8062012-11-22 00:10:41 -0800983Macros and variables starting with one or more underscores are private and
Armin Ronacher903d1682008-05-23 00:51:58 +0200984cannot be imported.
985
Armin Ronacher9165d3e2010-02-16 17:35:59 +0100986.. versionchanged:: 2.4
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600987 If a template object was passed to the template context, you can
Armin Ronacher9165d3e2010-02-16 17:35:59 +0100988 import from that object.
989
Armin Ronacherd84ec462008-04-29 13:43:16 +0200990
Armin Ronacherea847c52008-05-02 20:04:32 +0200991.. _import-visibility:
992
993Import Context Behavior
994-----------------------
995
Wes Turnerd40e9ba2014-12-11 05:24:53 -0600996By default, included templates are passed the current context and imported
997templates are not. The reason for this is that imports, unlike includes,
998are cached; as imports are often used just as a module that holds macros.
Armin Ronacherea847c52008-05-02 20:04:32 +0200999
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001000This behavior can be changed explicitly: by adding `with context`
1001or `without context` to the import/include directive, the current context
Armin Ronacherea847c52008-05-02 20:04:32 +02001002can be passed to the template and caching is disabled automatically.
1003
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001004Here are two examples::
Armin Ronacherea847c52008-05-02 20:04:32 +02001005
1006 {% from 'forms.html' import input with context %}
1007 {% include 'header.html' without context %}
1008
Armin Ronacher673aa882008-10-04 18:06:57 +02001009.. admonition:: Note
1010
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001011 In Jinja 2.0, the context that was passed to the included template
Armin Ronacher0aa0f582009-03-18 01:01:36 +01001012 did not include variables defined in the template. As a matter of
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001013 fact, this did not work::
Armin Ronacher673aa882008-10-04 18:06:57 +02001014
1015 {% for box in boxes %}
1016 {% include "render_box.html" %}
1017 {% endfor %}
1018
Alan Hogan02901a82011-04-28 20:18:55 -07001019 The included template ``render_box.html`` is *not* able to access
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001020 `box` in Jinja 2.0. As of Jinja 2.1, ``render_box.html`` *is* able
Alan Hogan02901a82011-04-28 20:18:55 -07001021 to do so.
Armin Ronacher673aa882008-10-04 18:06:57 +02001022
Armin Ronacherea847c52008-05-02 20:04:32 +02001023
Armin Ronacher709f6e52008-04-28 18:18:16 +02001024.. _expressions:
1025
1026Expressions
1027-----------
1028
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001029Jinja allows basic expressions everywhere. These work very similarly to
1030regular Python; even if you're not working with Python
1031you should feel comfortable with it.
Armin Ronacher709f6e52008-04-28 18:18:16 +02001032
1033Literals
1034~~~~~~~~
1035
1036The simplest form of expressions are literals. Literals are representations
1037for Python objects such as strings and numbers. The following literals exist:
1038
Armin Ronacher316157d2008-04-28 18:30:27 +02001039"Hello World":
Armin Ronacher709f6e52008-04-28 18:18:16 +02001040 Everything between two double or single quotes is a string. They are
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001041 useful whenever you need a string in the template (e.g. as
1042 arguments to function calls and filters, or just to extend or include a
Armin Ronacher709f6e52008-04-28 18:18:16 +02001043 template).
1044
Armin Ronacher316157d2008-04-28 18:30:27 +0200104542 / 42.23:
Armin Ronacher709f6e52008-04-28 18:18:16 +02001046 Integers and floating point numbers are created by just writing the
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001047 number down. If a dot is present, the number is a float, otherwise an
1048 integer. Keep in mind that, in Python, ``42`` and ``42.0``
1049 are different (``int`` and ``float``, respectively).
Armin Ronacher709f6e52008-04-28 18:18:16 +02001050
Armin Ronacher316157d2008-04-28 18:30:27 +02001051['list', 'of', 'objects']:
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001052 Everything between two brackets is a list. Lists are useful for storing
1053 sequential data to be iterated over. For example, you can easily
1054 create a list of links using lists and tuples for (and with) a for loop::
Armin Ronacher709f6e52008-04-28 18:18:16 +02001055
1056 <ul>
1057 {% for href, caption in [('index.html', 'Index'), ('about.html', 'About'),
1058 ('downloads.html', 'Downloads')] %}
1059 <li><a href="{{ href }}">{{ caption }}</a></li>
1060 {% endfor %}
1061 </ul>
1062
Armin Ronacher316157d2008-04-28 18:30:27 +02001063('tuple', 'of', 'values'):
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001064 Tuples are like lists that cannot be modified ("immutable"). If a tuple
1065 only has one item, it must be followed by a comma (``('1-tuple',)``).
1066 Tuples are usually used to represent items of two or more elements.
1067 See the list example above for more details.
Armin Ronacher709f6e52008-04-28 18:18:16 +02001068
Lukas Meuserad48a2e2008-05-01 18:19:57 +02001069{'dict': 'of', 'key': 'and', 'value': 'pairs'}:
Armin Ronacher709f6e52008-04-28 18:18:16 +02001070 A dict in Python is a structure that combines keys and values. Keys must
1071 be unique and always have exactly one value. Dicts are rarely used in
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001072 templates; they are useful in some rare cases such as the :func:`xmlattr`
Armin Ronacher709f6e52008-04-28 18:18:16 +02001073 filter.
1074
Armin Ronacher316157d2008-04-28 18:30:27 +02001075true / false:
Armin Ronacher9bb7e472008-05-28 11:26:59 +02001076 true is always true and false is always false.
1077
1078.. admonition:: Note
1079
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001080 The special constants `true`, `false`, and `none` are indeed lowercase.
1081 Because that caused confusion in the past, (`True` used to expand
1082 to an undefined variable that was considered false),
1083 all three can now also be written in title case
1084 (`True`, `False`, and `None`).
1085 However, for consistency, (all Jinja identifiers are lowercase)
1086 you should use the lowercase versions.
Armin Ronacher709f6e52008-04-28 18:18:16 +02001087
1088Math
1089~~~~
1090
1091Jinja allows you to calculate with values. This is rarely useful in templates
Armin Ronacher0aa0f582009-03-18 01:01:36 +01001092but exists for completeness' sake. The following operators are supported:
Armin Ronacher709f6e52008-04-28 18:18:16 +02001093
Armin Ronacher316157d2008-04-28 18:30:27 +02001094\+
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001095 Adds two objects together. Usually the objects are numbers, but if both are
1096 strings or lists, you can concatenate them this way. This, however, is not
1097 the preferred way to concatenate strings! For string concatenation, have
1098 a look-see at the ``~`` operator. ``{{ 1 + 1 }}`` is ``2``.
Armin Ronacher709f6e52008-04-28 18:18:16 +02001099
Armin Ronacher316157d2008-04-28 18:30:27 +02001100\-
Jakub Wilk3fc008b2013-05-25 23:37:34 +02001101 Subtract the second number from the first one. ``{{ 3 - 2 }}`` is ``1``.
Armin Ronacher709f6e52008-04-28 18:18:16 +02001102
Armin Ronacher316157d2008-04-28 18:30:27 +02001103/
Armin Ronacher709f6e52008-04-28 18:18:16 +02001104 Divide two numbers. The return value will be a floating point number.
1105 ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``.
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001106 (Just like ``from __future__ import division``.)
Armin Ronacher709f6e52008-04-28 18:18:16 +02001107
Armin Ronacher316157d2008-04-28 18:30:27 +02001108//
Armin Ronacher709f6e52008-04-28 18:18:16 +02001109 Divide two numbers and return the truncated integer result.
Fabian Topfstedt6ae12852011-05-22 08:19:12 -07001110 ``{{ 20 // 7 }}`` is ``2``.
Armin Ronacher709f6e52008-04-28 18:18:16 +02001111
Armin Ronacher316157d2008-04-28 18:30:27 +02001112%
Armin Ronacher0aa0f582009-03-18 01:01:36 +01001113 Calculate the remainder of an integer division. ``{{ 11 % 7 }}`` is ``4``.
Armin Ronacher709f6e52008-04-28 18:18:16 +02001114
Armin Ronacher316157d2008-04-28 18:30:27 +02001115\*
Armin Ronacher709f6e52008-04-28 18:18:16 +02001116 Multiply the left operand with the right one. ``{{ 2 * 2 }}`` would
Armin Ronacher0aa0f582009-03-18 01:01:36 +01001117 return ``4``. This can also be used to repeat a string multiple times.
Armin Ronacher709f6e52008-04-28 18:18:16 +02001118 ``{{ '=' * 80 }}`` would print a bar of 80 equal signs.
1119
Armin Ronacher316157d2008-04-28 18:30:27 +02001120\**
Armin Ronacher709f6e52008-04-28 18:18:16 +02001121 Raise the left operand to the power of the right operand. ``{{ 2**3 }}``
1122 would return ``8``.
1123
Armin Ronacher3c955322010-08-08 22:23:51 +02001124Comparisons
1125~~~~~~~~~~~
Armin Ronacher13203e12010-08-08 21:59:29 +02001126
1127==
1128 Compares two objects for equality.
1129
1130!=
1131 Compares two objects for inequality.
1132
1133>
1134 `true` if the left hand side is greater than the right hand side.
1135
1136>=
1137 `true` if the left hand side is greater or equal to the right hand side.
1138
1139<
1140 `true` if the left hand side is lower than the right hand side.
1141
1142<=
1143 `true` if the left hand side is lower or equal to the right hand side.
1144
Armin Ronacher709f6e52008-04-28 18:18:16 +02001145Logic
1146~~~~~
1147
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001148For `if` statements, `for` filtering, and `if` expressions, it can be useful to
Armin Ronacher0aa0f582009-03-18 01:01:36 +01001149combine multiple expressions:
Armin Ronacher709f6e52008-04-28 18:18:16 +02001150
Armin Ronacher316157d2008-04-28 18:30:27 +02001151and
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001152 Return true if the left and the right operand are true.
Armin Ronacher709f6e52008-04-28 18:18:16 +02001153
Armin Ronacher316157d2008-04-28 18:30:27 +02001154or
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001155 Return true if the left or the right operand are true.
Armin Ronacher709f6e52008-04-28 18:18:16 +02001156
Armin Ronacher316157d2008-04-28 18:30:27 +02001157not
Armin Ronacher709f6e52008-04-28 18:18:16 +02001158 negate a statement (see below).
1159
Armin Ronacher316157d2008-04-28 18:30:27 +02001160(expr)
Armin Ronacher709f6e52008-04-28 18:18:16 +02001161 group an expression.
1162
Armin Ronacher9bb7e472008-05-28 11:26:59 +02001163.. admonition:: Note
Armin Ronacher709f6e52008-04-28 18:18:16 +02001164
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001165 The ``is`` and ``in`` operators support negation using an infix notation,
Armin Ronacher9bb7e472008-05-28 11:26:59 +02001166 too: ``foo is not bar`` and ``foo not in bar`` instead of ``not foo is bar``
1167 and ``not foo in bar``. All other expressions require a prefix notation:
1168 ``not (foo and bar).``
Armin Ronacher709f6e52008-04-28 18:18:16 +02001169
1170
1171Other Operators
1172~~~~~~~~~~~~~~~
1173
1174The following operators are very useful but don't fit into any of the other
1175two categories:
1176
Armin Ronacher316157d2008-04-28 18:30:27 +02001177in
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001178 Perform a sequence / mapping containment test. Returns true if the left
1179 operand is contained in the right. ``{{ 1 in [1, 2, 3] }}`` would, for
1180 example, return true.
Armin Ronacher709f6e52008-04-28 18:18:16 +02001181
Armin Ronacher316157d2008-04-28 18:30:27 +02001182is
1183 Performs a :ref:`test <tests>`.
Armin Ronacher709f6e52008-04-28 18:18:16 +02001184
Armin Ronacher316157d2008-04-28 18:30:27 +02001185\|
1186 Applies a :ref:`filter <filters>`.
Armin Ronacher709f6e52008-04-28 18:18:16 +02001187
Armin Ronacher316157d2008-04-28 18:30:27 +02001188~
Armin Ronacher709f6e52008-04-28 18:18:16 +02001189 Converts all operands into strings and concatenates them.
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001190
1191 ``{{ "Hello " ~ name ~ "!" }}`` would return (assuming `name` is set
1192 to ``'John'``) ``Hello John!``.
Armin Ronacher709f6e52008-04-28 18:18:16 +02001193
Armin Ronacher316157d2008-04-28 18:30:27 +02001194()
Armin Ronacher709f6e52008-04-28 18:18:16 +02001195 Call a callable: ``{{ post.render() }}``. Inside of the parentheses you
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001196 can use positional arguments and keyword arguments like in Python:
1197
Armin Ronacher709f6e52008-04-28 18:18:16 +02001198 ``{{ post.render(user, full=true) }}``.
1199
Armin Ronacher316157d2008-04-28 18:30:27 +02001200. / []
Armin Ronacher709f6e52008-04-28 18:18:16 +02001201 Get an attribute of an object. (See :ref:`variables`)
1202
1203
1204.. _if-expression:
1205
1206If Expression
1207~~~~~~~~~~~~~
1208
Armin Ronacherb2a36aa2008-04-28 19:57:40 +02001209It is also possible to use inline `if` expressions. These are useful in some
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001210situations. For example, you can use this to extend from one template if a
Armin Ronacherd84ec462008-04-29 13:43:16 +02001211variable is defined, otherwise from the default layout template::
Armin Ronacherb2a36aa2008-04-28 19:57:40 +02001212
1213 {% extends layout_template if layout_template is defined else 'master.html' %}
Armin Ronacher709f6e52008-04-28 18:18:16 +02001214
Armin Ronacherd84ec462008-04-29 13:43:16 +02001215The general syntax is ``<do something> if <something is true> else <do
1216something else>``.
1217
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001218The `else` part is optional. If not provided, the else block implicitly
Armin Ronachera0e3ac02008-07-04 17:00:38 +02001219evaluates into an undefined object::
1220
1221 {{ '[%s]' % page.title if page.title }}
1222
Armin Ronacher157531b2008-04-28 16:14:03 +02001223
Armin Ronacher3c8b7ad2008-04-28 13:52:21 +02001224.. _builtin-filters:
1225
1226List of Builtin Filters
1227-----------------------
1228
1229.. jinjafilters::
1230
1231
1232.. _builtin-tests:
1233
1234List of Builtin Tests
1235---------------------
1236
Armin Ronacher157531b2008-04-28 16:14:03 +02001237.. jinjatests::
Armin Ronacher7259c762008-04-30 13:03:59 +02001238
Armin Ronacherccae0552008-10-05 23:08:58 +02001239.. _builtin-globals:
Armin Ronacher7259c762008-04-30 13:03:59 +02001240
1241List of Global Functions
1242------------------------
1243
1244The following functions are available in the global scope by default:
1245
1246.. function:: range([start,] stop[, step])
1247
1248 Return a list containing an arithmetic progression of integers.
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001249 ``range(i, j)`` returns ``[i, i+1, i+2, ..., j-1]``;
1250 start (!) defaults to ``0``.
Armin Ronacher7259c762008-04-30 13:03:59 +02001251 When step is given, it specifies the increment (or decrement).
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001252 For example, ``range(4)`` and ``range(0, 4, 1)`` return ``[0, 1, 2, 3]``.
1253 The end point is omitted!
Armin Ronacher7259c762008-04-30 13:03:59 +02001254 These are exactly the valid indices for a list of 4 elements.
1255
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001256 This is useful to repeat a template block multiple times, e.g.
Armin Ronacher19cf9c22008-05-01 12:49:53 +02001257 to fill a list. Imagine you have 7 users in the list but you want to
1258 render three empty items to enforce a height with CSS::
1259
1260 <ul>
1261 {% for user in users %}
1262 <li>{{ user.username }}</li>
1263 {% endfor %}
1264 {% for number in range(10 - users|count) %}
1265 <li class="empty"><span>...</span></li>
1266 {% endfor %}
1267 </ul>
1268
Armin Ronacher7259c762008-04-30 13:03:59 +02001269.. function:: lipsum(n=5, html=True, min=20, max=100)
1270
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001271 Generates some lorem ipsum for the template. By default, five paragraphs
1272 of HTML are generated with each paragraph between 20 and 100 words.
1273 If html is False, regular text is returned. This is useful to generate simple
Armin Ronacher7259c762008-04-30 13:03:59 +02001274 contents for layout testing.
Armin Ronacher76c280b2008-05-04 12:31:48 +02001275
Armin Ronachered98cac2008-05-07 08:42:11 +02001276.. function:: dict(\**items)
Armin Ronacher76c280b2008-05-04 12:31:48 +02001277
1278 A convenient alternative to dict literals. ``{'foo': 'bar'}`` is the same
1279 as ``dict(foo='bar')``.
Armin Ronachered98cac2008-05-07 08:42:11 +02001280
Armin Ronacherccae0552008-10-05 23:08:58 +02001281.. class:: cycler(\*items)
1282
1283 The cycler allows you to cycle among values similar to how `loop.cycle`
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001284 works. Unlike `loop.cycle`, you can use this cycler outside of
Armin Ronacherccae0552008-10-05 23:08:58 +02001285 loops or over multiple loops.
1286
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001287 This can be very useful if you want to show a list of folders and
1288 files with the folders on top but both in the same list with alternating
Armin Ronacherccae0552008-10-05 23:08:58 +02001289 row colors.
1290
1291 The following example shows how `cycler` can be used::
1292
1293 {% set row_class = cycler('odd', 'even') %}
1294 <ul class="browser">
1295 {% for folder in folders %}
1296 <li class="folder {{ row_class.next() }}">{{ folder|e }}</li>
1297 {% endfor %}
1298 {% for filename in files %}
1299 <li class="file {{ row_class.next() }}">{{ filename|e }}</li>
1300 {% endfor %}
1301 </ul>
1302
1303 A cycler has the following attributes and methods:
1304
1305 .. method:: reset()
1306
1307 Resets the cycle to the first item.
1308
1309 .. method:: next()
1310
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001311 Goes one item ahead and returns the then-current item.
Armin Ronacherccae0552008-10-05 23:08:58 +02001312
1313 .. attribute:: current
1314
1315 Returns the current item.
Andy McKay20044492011-06-30 14:40:05 -07001316
Armin Ronacherccae0552008-10-05 23:08:58 +02001317 **new in Jinja 2.1**
1318
Armin Ronacherd34eb122008-10-13 23:47:51 +02001319.. class:: joiner(sep=', ')
1320
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001321 A tiny helper that can be used to "join" multiple sections. A joiner is
Kevin Schuetzbc542b02011-07-26 14:16:46 -05001322 passed a string and will return that string every time it's called, except
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001323 the first time (in which case it returns an empty string). You can
Armin Ronacherd34eb122008-10-13 23:47:51 +02001324 use this to join things::
1325
1326 {% set pipe = joiner("|") %}
1327 {% if categories %} {{ pipe() }}
1328 Categories: {{ categories|join(", ") }}
1329 {% endif %}
1330 {% if author %} {{ pipe() }}
1331 Author: {{ author() }}
1332 {% endif %}
1333 {% if can_edit %} {{ pipe() }}
1334 <a href="?action=edit">Edit</a>
1335 {% endif %}
1336
1337 **new in Jinja 2.1**
1338
Armin Ronachered98cac2008-05-07 08:42:11 +02001339
1340Extensions
1341----------
1342
1343The following sections cover the built-in Jinja2 extensions that may be
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001344enabled by an application. An application could also provide further
1345extensions not covered by this documentation; in which case there should
1346be a separate document explaining said :ref:`extensions
1347<jinja-extensions>`.
Armin Ronachered98cac2008-05-07 08:42:11 +02001348
1349.. _i18n-in-templates:
1350
1351i18n
1352~~~~
1353
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001354If the i18n extension is enabled, it's possible to mark parts in the template
1355as translatable. To mark a section as translatable, you can use `trans`::
Armin Ronachered98cac2008-05-07 08:42:11 +02001356
1357 <p>{% trans %}Hello {{ user }}!{% endtrans %}</p>
1358
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001359To translate a template expression --- say, using template filters, or by just
Armin Ronachered98cac2008-05-07 08:42:11 +02001360accessing an attribute of an object --- you need to bind the expression to a
1361name for use within the translation block::
1362
1363 <p>{% trans user=user.username %}Hello {{ user }}!{% endtrans %}</p>
1364
1365If you need to bind more than one expression inside a `trans` tag, separate
1366the pieces with a comma (``,``)::
1367
1368 {% trans book_title=book.title, author=author.name %}
1369 This is {{ book_title }} by {{ author }}
1370 {% endtrans %}
1371
1372Inside trans tags no statements are allowed, only variable tags are.
1373
1374To pluralize, specify both the singular and plural forms with the `pluralize`
1375tag, which appears between `trans` and `endtrans`::
1376
1377 {% trans count=list|length %}
1378 There is {{ count }} {{ name }} object.
1379 {% pluralize %}
1380 There are {{ count }} {{ name }} objects.
1381 {% endtrans %}
1382
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001383By default, the first variable in a block is used to determine the correct
1384singular or plural form. If that doesn't work out, you can specify the name
Armin Ronachered98cac2008-05-07 08:42:11 +02001385which should be used for pluralizing by adding it as parameter to `pluralize`::
1386
1387 {% trans ..., user_count=users|length %}...
1388 {% pluralize user_count %}...{% endtrans %}
1389
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001390It's also possible to translate strings in expressions. For that purpose,
Armin Ronachered98cac2008-05-07 08:42:11 +02001391three functions exist:
1392
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001393- `gettext`: translate a single string
Armin Ronachered98cac2008-05-07 08:42:11 +02001394- `ngettext`: translate a pluralizable string
1395- `_`: alias for `gettext`
1396
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001397For example, you can easily print a translated string like this::
Armin Ronachered98cac2008-05-07 08:42:11 +02001398
1399 {{ _('Hello World!') }}
1400
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001401To use placeholders, use the `format` filter::
Armin Ronachered98cac2008-05-07 08:42:11 +02001402
1403 {{ _('Hello %(user)s!')|format(user=user.username) }}
Armin Ronachered98cac2008-05-07 08:42:11 +02001404
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001405For multiple placeholders, always use keyword arguments to `format`,
1406as other languages may not use the words in the same order.
Armin Ronacher5d2733f2008-05-15 23:26:52 +02001407
Armin Ronacherffaa2e72010-05-29 20:57:16 +02001408.. versionchanged:: 2.5
1409
Armin Ronacher8a3d93b2010-05-29 22:02:03 +02001410If newstyle gettext calls are activated (:ref:`newstyle-gettext`), using
Armin Ronacherffaa2e72010-05-29 20:57:16 +02001411placeholders is a lot easier:
1412
1413.. sourcecode:: html+jinja
1414
1415 {{ gettext('Hello World!') }}
1416 {{ gettext('Hello %(name)s!', name='World') }}
1417 {{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }}
1418
Kevin Schuetz522af5d2011-07-26 14:17:38 -05001419Note that the `ngettext` function's format string automatically receives
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001420the count as a `num` parameter in addition to the regular parameters.
Armin Ronacherffaa2e72010-05-29 20:57:16 +02001421
Armin Ronacher5d2733f2008-05-15 23:26:52 +02001422
Armin Ronacher61a5a242008-05-26 12:07:44 +02001423Expression Statement
1424~~~~~~~~~~~~~~~~~~~~
Armin Ronacher5d2733f2008-05-15 23:26:52 +02001425
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001426If the expression-statement extension is loaded, a tag called `do` is available
1427that works exactly like the regular variable expression (``{{ ... }}``); except
1428it doesn't print anything. This can be used to modify lists::
Armin Ronacher5d2733f2008-05-15 23:26:52 +02001429
1430 {% do navigation.append('a string') %}
Armin Ronacher3da90312008-05-23 16:37:28 +02001431
1432
1433Loop Controls
1434~~~~~~~~~~~~~
1435
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001436If the application enables the :ref:`loopcontrols-extension`, it's possible to
Armin Ronacher3da90312008-05-23 16:37:28 +02001437use `break` and `continue` in loops. When `break` is reached, the loop is
Kevin Schuetzc5855502011-07-26 14:21:52 -05001438terminated; if `continue` is reached, the processing is stopped and continues
Armin Ronacher3da90312008-05-23 16:37:28 +02001439with the next iteration.
1440
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001441Here's a loop that skips every second item::
Armin Ronacher3da90312008-05-23 16:37:28 +02001442
1443 {% for user in users %}
1444 {%- if loop.index is even %}{% continue %}{% endif %}
1445 ...
1446 {% endfor %}
1447
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001448Likewise, a loop that stops processing after the 10th iteration::
Armin Ronacher3da90312008-05-23 16:37:28 +02001449
1450 {% for user in users %}
1451 {%- if loop.index >= 10 %}{% break %}{% endif %}
1452 {%- endfor %}
Armin Ronacher9b4cc9f2010-02-07 03:55:15 +01001453
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001454Note that ``loop.index`` starts with 1, and ``loop.index0`` starts with 0
1455(See: :ref:`for-loop`).
1456
Armin Ronacher9b4cc9f2010-02-07 03:55:15 +01001457
1458With Statement
1459~~~~~~~~~~~~~~
1460
1461.. versionadded:: 2.3
1462
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001463If the application enables the :ref:`with-extension`, it is possible to
Armin Ronacher9b4cc9f2010-02-07 03:55:15 +01001464use the `with` keyword in templates. This makes it possible to create
1465a new inner scope. Variables set within this scope are not visible
1466outside of the scope.
1467
1468With in a nutshell::
1469
1470 {% with %}
1471 {% set foo = 42 %}
1472 {{ foo }} foo is 42 here
1473 {% endwith %}
1474 foo is not visible here any longer
1475
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001476Because it is common to set variables at the beginning of the scope,
1477you can do that within the `with` statement. The following two examples
Armin Ronacher9b4cc9f2010-02-07 03:55:15 +01001478are equivalent::
1479
1480 {% with foo = 42 %}
1481 {{ foo }}
1482 {% endwith %}
1483
1484 {% with %}
1485 {% set foo = 42 %}
1486 {{ foo }}
1487 {% endwith %}
Armin Ronacherfe150f32010-03-15 02:42:41 +01001488
Armin Ronacher752ba7f2010-04-05 18:17:27 +02001489.. _autoescape-overrides:
Armin Ronacherfe150f32010-03-15 02:42:41 +01001490
1491Autoescape Extension
1492--------------------
1493
1494.. versionadded:: 2.4
1495
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001496If the application enables the :ref:`autoescape-extension`, one can
Armin Ronacherfe150f32010-03-15 02:42:41 +01001497activate and deactivate the autoescaping from within the templates.
1498
1499Example::
1500
1501 {% autoescape true %}
1502 Autoescaping is active within this block
1503 {% endautoescape %}
1504
1505 {% autoescape false %}
1506 Autoescaping is inactive within this block
1507 {% endautoescape %}
1508
Wes Turnerd40e9ba2014-12-11 05:24:53 -06001509After an `endautoescape` the behavior is reverted to what it was before.