Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 1510 lines (1078 sloc) 48.702 kb
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
1 Template Designer Documentation
2 ===============================
3
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
4 .. highlight:: html+jinja
5
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
6 This document describes the syntax and semantics of the template engine and
7 will be most useful as reference to those creating Jinja templates. As the
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
8 template engine is very flexible, the configuration from the application can
459b908 @untitaker Not only syntax is affected.
untitaker authored
9 be slightly different from the code presented here in terms of delimiters and
10 behavior of undefined values.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
11
12
13 Synopsis
14 --------
15
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
16 A Jinja template is simply a text file. Jinja can generate any text-based
7ecfbe8 @untitaker We don't want to give a specific recommendation.
untitaker authored
17 format (HTML, XML, CSV, LaTeX, etc.). A Jinja template doesn't need to have a
18 specific extension: ``.html``, ``.xml``, or any other extension is just fine.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
19
0ce1bca @untitaker A few nitpicks
untitaker authored
20 A template contains **variables** and/or **expressions**, which get replaced
21 with values when a template is *rendered*; and **tags**, which control the
22 logic of the template. The template syntax is heavily inspired by Django and
23 Python.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
24
0ce1bca @untitaker A few nitpicks
untitaker authored
25 Below is a minimal template that illustrates a few basics using the default
26 Jinja configuration. We will cover the details later in this document::
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
27
b8230a7 @esonderegger Updated template documentation examples
esonderegger authored
28 <!DOCTYPE html>
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
29 <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 }}
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
42
43 {# a comment #}
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
44 </body>
45 </html>
46
0ce1bca @untitaker A few nitpicks
untitaker authored
47 The following example shows the default configuration settings. An application
48 developer can change the syntax configuration from ``{% foo %}`` to ``<% foo
49 %>``, or something similar.
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
50
51 There are a few kinds of delimiters. The default Jinja delimiters are
52 configured as follows:
53
0ce1bca @untitaker A few nitpicks
untitaker authored
54 * ``{% ... %}`` 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>`
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
58
59
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
60 .. _variables:
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
61
62 Variables
63 ---------
64
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
65 Template variables are defined by the context dictionary passed to the
66 template.
67
f30ab12 @thomasballinger docfixes in Variables section of templates.rst
thomasballinger authored
68 You can mess around with the variables in templates provided they are passed in
69 by the application. Variables may have attributes or elements on them you can
70 access too. What attributes a variable has depends heavily on the application
71 providing that variable.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
72
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
73 You can use a dot (``.``) to access attributes of a variable in addition
74 to the standard Python ``__getitem__`` "subscript" syntax (``[]``).
75
76 The following lines do the same thing::
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
77
78 {{ foo.bar }}
79 {{ foo['bar'] }}
80
0ce1bca @untitaker A few nitpicks
untitaker authored
81 It's important to know that the outer double-curly braces are *not* part of the
82 variable, but the print statement. If you access variables inside tags don't
83 put the braces around them.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
84
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
85 If a variable or attribute does not exist, you will get back an undefined
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
86 value. What you can do with that kind of value depends on the application
0ce1bca @untitaker A few nitpicks
untitaker authored
87 configuration: the default behavior is to evaluate to an empty string if
88 printed or iterated over, and to fail for every other operation.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
89
b938877 @mitsuhiko Changed all sentences with occurrences of subscribing to a similar sente...
authored
90 .. _notes-on-subscriptions:
6dc6f29 @mitsuhiko Improved attribute and item lookup by allowing template designers to exp...
authored
91
92 .. admonition:: Implementation
93
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
94 For the sake of convenience, ``foo.bar`` in Jinja2 does the following
0ce1bca @untitaker A few nitpicks
untitaker authored
95 things on the Python layer:
6dc6f29 @mitsuhiko Improved attribute and item lookup by allowing template designers to exp...
authored
96
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
97 - 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')``)
6dc6f29 @mitsuhiko Improved attribute and item lookup by allowing template designers to exp...
authored
101 - if there is not, return an undefined object.
102
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
103 ``foo['bar']`` works mostly the same with a small difference in sequence:
6dc6f29 @mitsuhiko Improved attribute and item lookup by allowing template designers to exp...
authored
104
0ce1bca @untitaker A few nitpicks
untitaker authored
105 - check for an item ``'bar'`` in `foo`.
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
106 (``foo.__getitem__('bar')``)
107 - if there is not, check for an attribute called `bar` on `foo`.
108 (``getattr(foo, 'bar')``)
6dc6f29 @mitsuhiko Improved attribute and item lookup by allowing template designers to exp...
authored
109 - if there is not, return an undefined object.
110
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
111 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.
6dc6f29 @mitsuhiko Improved attribute and item lookup by allowing template designers to exp...
authored
113
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
114 .. _filters:
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
115
116 Filters
117 -------
118
0614747 @mineo Fix a typo
mineo authored
119 Variables can be modified by **filters**. Filters are separated from the
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
120 variable by a pipe symbol (``|``) and may have optional arguments in
121 parentheses. Multiple filters can be chained. The output of one filter is
122 applied to the next.
123
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
124 For example, ``{{ name|striptags|title }}`` will remove all HTML Tags from
125 variable `name` and title-case the output (``title(striptags(name))``).
126
0ce1bca @untitaker A few nitpicks
untitaker authored
127 Filters that accept arguments have parentheses around the arguments, just like
128 a function call. For example: ``{{ listx|join(', ') }}`` will join a list with
129 commas (``str.join(', ', listx)``).
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
130
157531b @mitsuhiko more docs and fixed bug in parser that assigned lineno for ExprStmt wron...
authored
131 The :ref:`builtin-filters` below describes all the builtin filters.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
132
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
133 .. _tests:
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
134
135 Tests
136 -----
137
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
138 Beside filters, there are also so-called "tests" available. Tests can be used
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
139 to test a variable against a common expression. To test a variable or
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
140 expression, you add `is` plus the name of the test after the variable. For
141 example, to find out if a variable is defined, you can do ``name is defined``,
142 which will then return true or false depending on whether `name` is defined
143 in the current template context.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
144
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
145 Tests can accept arguments, too. If the test only takes one argument, you can
146 leave out the parentheses. For example, the following two
147 expressions do the same thing::
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
148
149 {% if loop.index is divisibleby 3 %}
150 {% if loop.index is divisibleby(3) %}
151
ad48a2e Fixed typos in documentation
Lukas Meuser authored
152 The :ref:`builtin-tests` below describes all the builtin tests.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
153
154
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
155 .. _comments:
156
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
157 Comments
158 --------
159
160 To comment-out part of a line in a template, use the comment syntax which is
161 by default set to ``{# ... #}``. This is useful to comment out parts of the
162 template for debugging or to add information for other template designers or
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
163 yourself::
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
164
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
165 {# note: commented-out template because we no longer use this
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
166 {% for user in users %}
167 ...
168 {% endfor %}
169 #}
170
f35e281 @mitsuhiko some documentation improvements, jinja escapes " and ' now, both into ch...
authored
171
172 Whitespace Control
173 ------------------
174
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
175 In the default configuration:
176
177 * a single trailing newline is stripped if present
0ce1bca @untitaker A few nitpicks
untitaker authored
178 * other whitespace (spaces, tabs, newlines etc.) is returned unchanged
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
179
180 If an application configures Jinja to `trim_blocks`, the first newline after a
214bb36 @kristi document `lstrip_blocks`
kristi authored
181 template tag is removed automatically (like in PHP). The `lstrip_blocks`
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
182 option can also be set to strip tabs and spaces from the beginning of a
214bb36 @kristi document `lstrip_blocks`
kristi authored
183 line to the start of a block. (Nothing will be stripped if there are
184 other characters before the start of the block.)
185
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
186 With both `trim_blocks` and `lstrip_blocks` enabled, you can put block tags
214bb36 @kristi document `lstrip_blocks`
kristi authored
187 on their own lines, and the entire block line will be removed when
188 rendered, preserving the whitespace of the contents. For example,
189 without the `trim_blocks` and `lstrip_blocks` options, this template::
190
191 <div>
192 {% if True %}
193 yay
194 {% endif %}
195 </div>
196
197 gets rendered with blank lines inside the div::
198
199 <div>
200
201 yay
202
203 </div>
204
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
205 But with both `trim_blocks` and `lstrip_blocks` enabled, the template block
206 lines are removed and other whitespace is preserved::
214bb36 @kristi document `lstrip_blocks`
kristi authored
207
208 <div>
209 yay
210 </div>
211
e4a74f9 @kristi Document the {%+ manual disable lstrip_blocks feature
kristi authored
212 You can manually disable the `lstrip_blocks` behavior by putting a
213 plus sign (``+``) at the start of a block::
214
215 <div>
216 {%+ if something %}yay{% endif %}
217 </div>
218
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
219 You can also strip whitespace in templates by hand. If you add a minus
220 sign (``-``) to the start or end of a block (e.g. a :ref:`for-loop` tag), a
221 comment, or a variable expression, the whitespaces before or after
222 that block will be removed::
f35e281 @mitsuhiko some documentation improvements, jinja escapes " and ' now, both into ch...
authored
223
224 {% for item in seq -%}
225 {{ item }}
226 {%- endfor %}
2004449 @andymckay fix typo
andymckay authored
227
f35e281 @mitsuhiko some documentation improvements, jinja escapes " and ' now, both into ch...
authored
228 This will yield all elements without whitespace between them. If `seq` was
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
229 a list of numbers from ``1`` to ``9``, the output would be ``123456789``.
f35e281 @mitsuhiko some documentation improvements, jinja escapes " and ' now, both into ch...
authored
230
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
231 If :ref:`line-statements` are enabled, they strip leading whitespace
9bb7e47 @mitsuhiko some more documentation updates and minor code cleanups. Additionally T...
authored
232 automatically up to the beginning of the line.
233
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
234 By default, Jinja2 also removes trailing newlines. To keep single
235 trailing newlines, configure Jinja to `keep_trailing_newline`.
a65f1eb @mitsuhiko Merge remote-tracking branch 'kristi/master'
authored
236
9bb7e47 @mitsuhiko some more documentation updates and minor code cleanups. Additionally T...
authored
237 .. admonition:: Note
f35e281 @mitsuhiko some documentation improvements, jinja escapes " and ' now, both into ch...
authored
238
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
239 You must not add whitespace between the tag and the minus sign.
9bb7e47 @mitsuhiko some more documentation updates and minor code cleanups. Additionally T...
authored
240
241 **valid**::
61a5a24 @mitsuhiko fixed a bug in error reporting and some small documentation updates
authored
242
f35e281 @mitsuhiko some documentation improvements, jinja escapes " and ' now, both into ch...
authored
243 {%- if foo -%}...{% endif %}
244
9bb7e47 @mitsuhiko some more documentation updates and minor code cleanups. Additionally T...
authored
245 **invalid**::
f35e281 @mitsuhiko some documentation improvements, jinja escapes " and ' now, both into ch...
authored
246
247 {% - if foo - %}...{% endif %}
248
249
250 Escaping
251 --------
252
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
253 It is sometimes desirable -- even necessary -- to have Jinja ignore parts
254 it would otherwise handle as variables or blocks. For example, if, with
255 the default syntax, you want to use ``{{`` as a raw string in a template and
256 not start a variable, you have to use a trick.
f35e281 @mitsuhiko some documentation improvements, jinja escapes " and ' now, both into ch...
authored
257
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
258 The easiest way to output a literal variable delimiter (``{{``) is by using a
f35e281 @mitsuhiko some documentation improvements, jinja escapes " and ' now, both into ch...
authored
259 variable expression::
260
261 {{ '{{' }}
262
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
263 For bigger sections, it makes sense to mark a block `raw`. For example, to
264 include example Jinja syntax in a template, you can use this snippet::
f35e281 @mitsuhiko some documentation improvements, jinja escapes " and ' now, both into ch...
authored
265
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
277 Line Statements
278 ---------------
279
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
280 If line statements are enabled by the application, it's possible to mark a
281 line as a statement. For example, if the line statement prefix is configured
282 to ``#``, the following two examples are equivalent::
f35e281 @mitsuhiko some documentation improvements, jinja escapes " and ' now, both into ch...
authored
283
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
296 The line statement prefix can appear anywhere on the line as long as no text
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
297 precedes it. For better readability, statements that start a block (such as
f35e281 @mitsuhiko some documentation improvements, jinja escapes " and ' now, both into ch...
authored
298 `for`, `if`, `elif` etc.) may end with a colon::
299
300 # for item in seq:
301 ...
ac61b24 @birkenfeld Fix two typos.
birkenfeld authored
302 # endfor
f35e281 @mitsuhiko some documentation improvements, jinja escapes " and ' now, both into ch...
authored
303
304
3ef2043 @mitsuhiko updated documentation
authored
305 .. 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
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
317 Since Jinja 2.2, line-based comments are available as well. For example, if
318 the line-comment prefix is configured to be ``##``, everything from ``##`` to
59b6bd5 @mitsuhiko Added support for line-based comments.
authored
319 the 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
3ef2043 @mitsuhiko updated documentation
authored
325
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
326 .. _template-inheritance:
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
327
328 Template Inheritance
329 --------------------
330
331 The most powerful part of Jinja is template inheritance. Template inheritance
332 allows you to build a base "skeleton" template that contains all the common
333 elements of your site and defines **blocks** that child templates can override.
334
335 Sounds complicated but is very basic. It's easiest to understand it by starting
336 with an example.
337
338
339 Base Template
340 ~~~~~~~~~~~~~
341
342 This template, which we'll call ``base.html``, defines a simple HTML skeleton
343 document that you might use for a simple two-column page. It's the job of
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
344 "child" templates to fill the empty blocks with content::
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
345
b8230a7 @esonderegger Updated template documentation examples
esonderegger authored
346 <!DOCTYPE html>
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
347 <html lang="en">
348 <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>
b8230a7 @esonderegger Updated template documentation examples
esonderegger authored
362 </html>
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
363
364 In this example, the ``{% block %}`` tags define four blocks that child templates
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
365 can fill in. All the `block` tag does is tell the template engine that a
366 child template may override those placeholders in the template.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
367
368 Child Template
369 ~~~~~~~~~~~~~~
370
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
371 A child template might look like this::
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
372
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">
cf845c9 @cerivera grammar fix
cerivera authored
384 Welcome to my awesome homepage.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
385 </p>
386 {% endblock %}
387
388 The ``{% extends %}`` tag is the key here. It tells the template engine that
389 this template "extends" another template. When the template system evaluates
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
390 this template, it first locates the parent. The extends tag should be the
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
391 first tag in the template. Everything before it is printed out normally and
fdf9530 @mitsuhiko added parsing code for "for item in seq recursive" and improved parser i...
authored
392 may cause confusion. For details about this behavior and how to take
393 advantage of it, see :ref:`null-master-fallback`.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
394
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
395 The filename of the template depends on the template loader. For example, the
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
396 :class:`FileSystemLoader` allows you to access other templates by giving the
a21f2ed @Cito Fix typos.
Cito authored
397 filename. You can access templates in subdirectories with a slash::
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
398
399 {% extends "layout/default.html" %}
400
401 But this behavior can depend on the application embedding Jinja. Note that
402 since the child template doesn't define the ``footer`` block, the value from
403 the parent template is used instead.
404
405 You can't define multiple ``{% block %}`` tags with the same name in the
406 same template. This limitation exists because a block tag works in "both"
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
407 directions. 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*.
409 If there were two similarly-named ``{% block %}`` tags in a template,
410 that template's parent wouldn't know which one of the blocks' content to use.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
411
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
412 If you want to print a block multiple times, you can, however, use the special
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
413 `self` variable and call the block with that name::
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
414
415 <title>{% block title %}{% endblock %}</title>
416 <h1>{{ self.title() }}</h1>
417 {% block body %}{% endblock %}
418
419
420 Super Blocks
421 ~~~~~~~~~~~~
422
423 It's possible to render the contents of the parent block by calling `super`.
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
424 This gives back the results of the parent block::
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
425
426 {% block sidebar %}
427 <h3>Table Of Contents</h3>
428 ...
429 {{ super() }}
430 {% endblock %}
431
432
fd31049 @mitsuhiko all calls are proxied by context.call now so that we can inject environm...
authored
433 Named Block End-Tags
434 ~~~~~~~~~~~~~~~~~~~~
435
436 Jinja2 allows you to put the name of the block after the end tag for better
437 readability::
438
439 {% block sidebar %}
440 {% block inner_sidebar %}
441 ...
442 {% endblock inner_sidebar %}
443 {% endblock sidebar %}
444
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
445 However, the name after the `endblock` word must match the block name.
fd31049 @mitsuhiko all calls are proxied by context.call now so that we can inject environm...
authored
446
447
74a0cd9 @mitsuhiko Added support for optional `scoped` modifier to blocks.
authored
448 Block Nesting and Scope
449 ~~~~~~~~~~~~~~~~~~~~~~~
450
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
451 Blocks can be nested for more complex layouts. However, per default blocks
74a0cd9 @mitsuhiko Added support for optional `scoped` modifier to blocks.
authored
452 may not access variables from outer scopes::
453
454 {% for item in seq %}
455 <li>{% block loop_item %}{{ item }}{% endblock %}</li>
456 {% endfor %}
457
458 This example would output empty ``<li>`` items because `item` is unavailable
459 inside the block. The reason for this is that if the block is replaced by
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
460 a child template, a variable would appear that was not defined in the block or
74a0cd9 @mitsuhiko Added support for optional `scoped` modifier to blocks.
authored
461 passed to the context.
462
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
463 Starting with Jinja 2.2, you can explicitly specify that variables are
74a0cd9 @mitsuhiko Added support for optional `scoped` modifier to blocks.
authored
464 available in a block by setting the block to "scoped" by adding the `scoped`
465 modifier to a block declaration::
466
467 {% for item in seq %}
468 <li>{% block loop_item scoped %}{{ item }}{% endblock %}</li>
469 {% endfor %}
470
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
471 When overriding a block, the `scoped` modifier does not have to be provided.
74a0cd9 @mitsuhiko Added support for optional `scoped` modifier to blocks.
authored
472
473
9165d3e @mitsuhiko the environment template loading functions now transparently
authored
474 Template Objects
475 ~~~~~~~~~~~~~~~~
476
477 .. versionchanged:: 2.4
478
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
479 If a template object was passed in the template context, you can
9165d3e @mitsuhiko the environment template loading functions now transparently
authored
480 extend from that object as well. Assuming the calling code passes
481 a layout template as `layout_template` to the environment, this
482 code works::
483
484 {% extends layout_template %}
485
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
486 Previously, the `layout_template` variable had to be a string with
9165d3e @mitsuhiko the environment template loading functions now transparently
authored
487 the layout template's filename for this to work.
488
489
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
490 HTML Escaping
491 -------------
492
493 When generating HTML from templates, there's always a risk that a variable will
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
494 include characters that affect the resulting HTML. There are two approaches:
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
495
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
496 a. manually escaping each variable; or
497 b. automatically escaping everything by default.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
498
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
499 Jinja supports both. What is used depends on the application configuration.
500 The 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.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
505
506 - The information about the safety of a variable is very fragile. It could
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
507 happen that by coercing safe and unsafe values, the return value is
508 double-escaped HTML.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
509
510 Working with Manual Escaping
157531b @mitsuhiko more docs and fixed bug in parser that assigned lineno for ExprStmt wron...
authored
511 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
512
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
513 If manual escaping is enabled, it's **your** responsibility to escape
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
514 variables if needed. What to escape? If you have a variable that *may*
515 include any of the following chars (``>``, ``<``, ``&``, or ``"``) you
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
516 **SHOULD** escape it unless the variable contains well-formed and trusted
517 HTML. Escaping works by piping the variable through the ``|e`` filter::
518
519 {{ user.username|e }}
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
520
521 Working with Automatic Escaping
157531b @mitsuhiko more docs and fixed bug in parser that assigned lineno for ExprStmt wron...
authored
522 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
523
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
524 When automatic escaping is enabled, everything is escaped by default except
525 for values explicitly marked as safe. Variables and expressions
526 can be marked as safe either in:
527
528 a. the context dictionary by the application with `MarkupSafe.Markup`, or
529 b. the template, with the `|safe` filter
530
0ce1bca @untitaker A few nitpicks
untitaker authored
531 The main problem with this approach is that Python itself doesn't have the
532 concept of tainted values; so whether a value is safe or unsafe can get lost.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
533
0ce1bca @untitaker A few nitpicks
untitaker authored
534 If a value is not marked safe, auto-escaping will take place; which means that
535 you could end up with double-escaped contents. Double-escaping is easy to
536 avoid, however: just rely on the tools Jinja2 provides and *don't use builtin
537 Python constructs such as str.format or the string modulo operator (%)*.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
538
0ce1bca @untitaker A few nitpicks
untitaker authored
539 Jinja2 functions (macros, `super`, `self.BLOCKNAME`) always return template
540 data that is marked as safe.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
541
542 String literals in templates with automatic escaping are considered unsafe
0ce1bca @untitaker A few nitpicks
untitaker authored
543 because native Python strings (``str``, ``unicode``, ``basestring``) are not
544 `MarkupSafe.Markup` strings with an ``__html__`` attribute.
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
545
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
546 .. _list-of-control-structures:
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
547
157531b @mitsuhiko more docs and fixed bug in parser that assigned lineno for ExprStmt wron...
authored
548 List of Control Structures
549 --------------------------
550
551 A control structure refers to all those things that control the flow of a
552 program - conditionals (i.e. if/elif/else), for-loops, as well as things like
0ce1bca @untitaker A few nitpicks
untitaker authored
553 macros and blocks. With the default syntax, control structures appear inside
554 ``{% ... %}`` blocks.
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
555
556 .. _for-loop:
157531b @mitsuhiko more docs and fixed bug in parser that assigned lineno for ExprStmt wron...
authored
557
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
558 For
559 ~~~
157531b @mitsuhiko more docs and fixed bug in parser that assigned lineno for ExprStmt wron...
authored
560
ad48a2e Fixed typos in documentation
Lukas Meuser authored
561 Loop over each item in a sequence. For example, to display a list of users
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
562 provided in a variable called `users`::
157531b @mitsuhiko more docs and fixed bug in parser that assigned lineno for ExprStmt wron...
authored
563
564 <h1>Members</h1>
565 <ul>
566 {% for user in users %}
567 <li>{{ user.username|e }}</li>
568 {% endfor %}
569 </ul>
570
898975d @mitsuhiko Added a dict iteration example. This fixes #64
authored
571 As variables in templates retain their object properties, it is possible to
572 iterate 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
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
581 Note, however, that **Python dicts are not ordered**; so you might want to
0ce1bca @untitaker A few nitpicks
untitaker authored
582 either pass a sorted ``list`` of ``tuple`` s -- or a
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
583 ``collections.OrderedDict`` -- to the template, or use the `dictsort` filter.
898975d @mitsuhiko Added a dict iteration example. This fixes #64
authored
584
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
585 Inside of a for-loop block, you can access some special variables:
157531b @mitsuhiko more docs and fixed bug in parser that assigned lineno for ExprStmt wron...
authored
586
587 +-----------------------+---------------------------------------------------+
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
588 | Variable | Description |
589 +=======================+===================================================+
157531b @mitsuhiko more docs and fixed bug in parser that assigned lineno for ExprStmt wron...
authored
590 | `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 +-----------------------+---------------------------------------------------+
568352e @mitsuhiko Documented loop.depth and added loop.depth0.
authored
609 | `loop.depth` | Indicates how deep in deep in a recursive loop |
610 | | the rendering currently is. Starts at level 1 |
611 +-----------------------+---------------------------------------------------+
da94a8b @mitsuhiko Fixed docs not building
authored
612 | `loop.depth0` | Indicates how deep in deep in a recursive loop |
568352e @mitsuhiko Documented loop.depth and added loop.depth0.
authored
613 | | the rendering currently is. Starts at level 0 |
614 +-----------------------+---------------------------------------------------+
157531b @mitsuhiko more docs and fixed bug in parser that assigned lineno for ExprStmt wron...
authored
615
ad48a2e Fixed typos in documentation
Lukas Meuser authored
616 Within a for-loop, it's possible to cycle among a list of strings/variables
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
617 each time through the loop by using the special `loop.cycle` helper::
157531b @mitsuhiko more docs and fixed bug in parser that assigned lineno for ExprStmt wron...
authored
618
619 {% for row in rows %}
620 <li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>
621 {% endfor %}
622
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
623 Since Jinja 2.1, an extra `cycle` helper exists that allows loop-unbound
624 cycling. For more information, have a look at the :ref:`builtin-globals`.
ccae055 @mitsuhiko Various cleanups and added custom cycler.
authored
625
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
626 .. _loop-filtering:
627
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
628 Unlike in Python, it's not possible to `break` or `continue` in a loop. You
629 can, however, filter the sequence during iteration, which allows you to skip
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
630 items. The following example skips all the users which are hidden::
157531b @mitsuhiko more docs and fixed bug in parser that assigned lineno for ExprStmt wron...
authored
631
632 {% for user in users if not user.hidden %}
633 <li>{{ user.username|e }}</li>
634 {% endfor %}
635
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
636 The advantage is that the special `loop` variable will count correctly; thus
157531b @mitsuhiko more docs and fixed bug in parser that assigned lineno for ExprStmt wron...
authored
637 not counting the users not iterated over.
638
639 If no iteration took place because the sequence was empty or the filtering
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
640 removed all the items from the sequence, you can render a default block
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
641 by using `else`::
157531b @mitsuhiko more docs and fixed bug in parser that assigned lineno for ExprStmt wron...
authored
642
643 <ul>
644 {% for user in users %}
645 <li>{{ user.username|e }}</li>
646 {% else %}
647 <li><em>no users found</em></li>
890dac0 @mitsuhiko Fixed typo in documentation.
authored
648 {% endfor %}
157531b @mitsuhiko more docs and fixed bug in parser that assigned lineno for ExprStmt wron...
authored
649 </ul>
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
650
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
651 Note that, in Python, `else` blocks are executed whenever the corresponding
652 loop **did not** `break`. Since Jinja loops cannot `break` anyway,
4780c2c @Cito Add a note about the else statement.
Cito authored
653 a slightly different behavior of the `else` keyword was chosen.
654
1de4c64 @mitsuhiko documented recursive loops
authored
655 It is also possible to use loops recursively. This is useful if you are
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
656 dealing with recursive data such as sitemaps or RDFa.
657 To use loops recursively, you basically have to add the `recursive` modifier
658 to the loop definition and call the `loop` variable with the new iterable
659 where you want to recurse.
1de4c64 @mitsuhiko documented recursive loops
authored
660
661 The 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
aa023e4 @myle Update docs/templates.rst
myle authored
672 The `loop` variable always refers to the closest (innermost) loop. If we
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
673 have more than one level of loops, we can rebind the variable `loop` by
aa023e4 @myle Update docs/templates.rst
myle authored
674 writing `{% set outer_loop = loop %}` after the loop that we want to
675 use recursively. Then, we can call it using `{{ outer_loop(...) }}`
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
676
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
677 .. _if:
678
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
679 If
680 ~~
681
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
682 The `if` statement in Jinja is comparable with the Python if statement.
683 In the simplest form, you can use it to test if a variable is defined, not
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
684 empty or not false::
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
685
686 {% if users %}
687 <ul>
688 {% for user in users %}
689 <li>{{ user.username|e }}</li>
690 {% endfor %}
691 </ul>
692 {% endif %}
693
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
694 For multiple branches, `elif` and `else` can be used like in Python. You can
695 use more complex :ref:`expressions` there, too::
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
696
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
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
705 If can also be used as an :ref:`inline expression <if-expression>` and for
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
706 :ref:`loop filtering <loop-filtering>`.
707
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
708 .. _macros:
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
709
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
710 Macros
711 ~~~~~~
712
ad48a2e Fixed typos in documentation
Lukas Meuser authored
713 Macros are comparable with functions in regular programming languages. They
714 are useful to put often used idioms into reusable functions to not repeat
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
715 yourself ("DRY").
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
716
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
717 Here's a small example of a macro that renders a form element::
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
718
719 {% macro input(name, value='', type='text', size=20) -%}
720 <input type="{{ type }}" name="{{ name }}" value="{{
721 value|e }}" size="{{ size }}">
722 {%- endmacro %}
723
724 The 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
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
729 If the macro was defined in a different template, you have to
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
730 :ref:`import <import>` it first.
731
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
732 Inside macros, you have access to three special variables:
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
733
734 `varargs`
ad48a2e Fixed typos in documentation
Lukas Meuser authored
735 If more positional arguments are passed to the macro than accepted by the
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
736 macro, they end up in the special `varargs` variable as a list of values.
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
737
738 `kwargs`
739 Like `varargs` but for keyword arguments. All unconsumed keyword
740 arguments are stored in this special variable.
741
742 `caller`
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
743 If the macro was called from a :ref:`call<call>` tag, the caller is stored
744 in this variable as a callable macro.
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
745
746 Macros also expose some of their internal details. The following attributes
747 are 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`
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
759 This is `true` if the macro accepts extra keyword arguments (i.e.: accesses
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
760 the special `kwargs` variable).
761
762 `catch_varargs`
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
763 This is `true` if the macro accepts extra positional arguments (i.e.:
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
764 accesses the special `varargs` variable).
765
766 `caller`
767 This is `true` if the macro accesses the special `caller` variable and may
ad48a2e Fixed typos in documentation
Lukas Meuser authored
768 be called from a :ref:`call<call>` tag.
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
769
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
770 If a macro name starts with an underscore, it's not exported and can't
c347ed0 @mitsuhiko Unified some code in the super/template reference system.
authored
771 be imported.
772
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
773
774 .. _call:
775
776 Call
777 ~~~~
778
779 In some cases it can be useful to pass a macro to another macro. For this
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
780 purpose, you can use the special `call` block. The following example shows
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
781 a macro that takes advantage of the call functionality and how it can be
782 used::
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
798 It's also possible to pass arguments back to the call block. This makes it
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
799 useful as a replacement for loops. Generally speaking, a call block works
800 exactly like a macro without a name.
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
801
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
802 Here's an example of how a call block can be used with arguments::
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
803
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
76f9aa4 @mitsuhiko Altered filesizeformat to support both MB and MiB, documented `{% filter...
authored
822 Filters
823 ~~~~~~~
824
825 Filter sections allow you to apply regular Jinja2 filters on a block of
826 template data. Just wrap the code in the special `filter` section::
827
828 {% filter upper %}
829 This text becomes uppercase
830 {% endfilter %}
831
832
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
833 .. _assignments:
834
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
835 Assignments
836 ~~~~~~~~~~~
837
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
838 Inside code blocks, you can also assign values to variables. Assignments at
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
839 top level (outside of blocks, macros or loops) are exported from the template
840 like top level macros and can be imported by other templates.
841
2e30cf5 @mitsuhiko documented set changes
authored
842 Assignments use the `set` tag and can have multiple targets::
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
843
2e30cf5 @mitsuhiko documented set changes
authored
844 {% set navigation = [('index.html', 'Index'), ('about.html', 'About')] %}
845 {% set key, value = call_something() %}
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
846
847
3d91ae5 @mitsuhiko Documented {% set %}...{% endset %}
authored
848 Block Assignments
849 ~~~~~~~~~~~~~~~~~
850
851 .. versionadded:: 2.8
852
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
853 Starting with Jinja 2.8, it's possible to also use block assignments to
3d91ae5 @mitsuhiko Documented {% set %}...{% endset %}
authored
854 capture the contents of a block into a variable name. This can be useful
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
855 in some situations as an alternative for macros. In that case, instead of
856 using an equals sign and a value, you just write the variable name and then
3d91ae5 @mitsuhiko Documented {% set %}...{% endset %}
authored
857 everything until ``{% endset %}`` is captured.
858
859 Example::
860
861 {% set navigation %}
862 <li><a href="/">Index</a>
863 <li><a href="/downloads">Downloads</a>
864 {% endset %}
865
866 The `navigation` variable then contains the navigation HTML source.
867
868
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
869 .. _extends:
870
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
871 Extends
872 ~~~~~~~
873
0ce1bca @untitaker A few nitpicks
untitaker authored
874 The `extends` tag can be used to extend one template from another. You can
875 have multiple `extends` tags in a file, but only one of them may be executed at
876 a time.
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
877
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
878 See the section about :ref:`template-inheritance` above.
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
879
880
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
881 .. _blocks:
882
883 Blocks
884 ~~~~~~
885
886 Blocks are used for inheritance and act as both placeholders and replacements
887 at the same time. They are documented in detail in the
888 :ref:`template-inheritance` section.
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
889
890
891 Include
892 ~~~~~~~
893
894 The `include` statement is useful to include a template and return the
895 rendered contents of that file into the current namespace::
896
897 {% include 'header.html' %}
898 Body
899 {% include 'footer.html' %}
900
ea847c5 @mitsuhiko added "with context" or "without context" import/include modifiers
authored
901 Included templates have access to the variables of the active context by
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
902 default. For more details about context behavior of imports and includes,
ea847c5 @mitsuhiko added "with context" or "without context" import/include modifiers
authored
903 see :ref:`import-visibility`.
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
904
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
905 From Jinja 2.2 onwards, you can mark an include with ``ignore missing``; in
200fe17 @dmedvinsky Fix typo in `include` documentation
dmedvinsky authored
906 which case Jinja will ignore the statement if the template to be included
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
907 does not exist. When combined with ``with`` or ``without context``, it must
908 be placed *before* the context visibility statement. Here are some valid
37f58ce @mitsuhiko Include statements can now be marked with ``ignore missing`` to skip
authored
909 examples::
910
911 {% include "sidebar.html" ignore missing %}
912 {% include "sidebar.html" ignore missing with context %}
913 {% include "sidebar.html" ignore missing without context %}
914
31bbd9e @mitsuhiko include tags are now able to select between multiple templates
authored
915 .. versionadded:: 2.2
916
917 You can also provide a list of templates that are checked for existence
918 before inclusion. The first template that exists will be included. If
919 `ignore missing` is given, it will fall back to rendering nothing if
920 none of the templates exist, otherwise it will raise an exception.
921
922 Example::
923
924 {% include ['page_detailed.html', 'page.html'] %}
925 {% include ['special_sidebar.html', 'sidebar.html'] ignore missing %}
926
9165d3e @mitsuhiko the environment template loading functions now transparently
authored
927 .. versionchanged:: 2.4
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
928 If a template object was passed to the template context, you can
9165d3e @mitsuhiko the environment template loading functions now transparently
authored
929 include that object using `include`.
930
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
931 .. _import:
932
933 Import
934 ~~~~~~
935
936 Jinja2 supports putting often used code into macros. These macros can go into
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
937 different templates and get imported from there. This works similarly to the
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
938 import statements in Python. It's important to know that imports are cached
939 and imported templates don't have access to the current template variables,
a21f2ed @Cito Fix typos.
Cito authored
940 just the globals by default. For more details about context behavior of
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
941 imports and includes, see :ref:`import-visibility`.
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
942
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
943 There are two ways to import templates. You can import a complete template
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
944 into a variable or request specific macros / exported variables from it.
945
946 Imagine 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
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
957 The easiest and most flexible way to access a template's variables
958 and macros is to import the whole template module into a variable.
959 That way, you can access the attributes::
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
960
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
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
971 Alternatively, you can import specific names from a template into the current
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
972 namespace::
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
63bd806 @kuyan Fixed typo
kuyan authored
983 Macros and variables starting with one or more underscores are private and
903d168 @mitsuhiko variables starting with one or more underscores are not exported
authored
984 cannot be imported.
985
9165d3e @mitsuhiko the environment template loading functions now transparently
authored
986 .. versionchanged:: 2.4
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
987 If a template object was passed to the template context, you can
9165d3e @mitsuhiko the environment template loading functions now transparently
authored
988 import from that object.
989
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
990
ea847c5 @mitsuhiko added "with context" or "without context" import/include modifiers
authored
991 .. _import-visibility:
992
993 Import Context Behavior
994 -----------------------
995
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
996 By default, included templates are passed the current context and imported
997 templates are not. The reason for this is that imports, unlike includes,
998 are cached; as imports are often used just as a module that holds macros.
ea847c5 @mitsuhiko added "with context" or "without context" import/include modifiers
authored
999
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1000 This behavior can be changed explicitly: by adding `with context`
1001 or `without context` to the import/include directive, the current context
ea847c5 @mitsuhiko added "with context" or "without context" import/include modifiers
authored
1002 can be passed to the template and caching is disabled automatically.
1003
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1004 Here are two examples::
ea847c5 @mitsuhiko added "with context" or "without context" import/include modifiers
authored
1005
1006 {% from 'forms.html' import input with context %}
1007 {% include 'header.html' without context %}
1008
673aa88 @mitsuhiko imports and includes "with context" are passed the full context now, not...
authored
1009 .. admonition:: Note
1010
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1011 In Jinja 2.0, the context that was passed to the included template
0aa0f58 @mitsuhiko Applied documentation patches by Clemens Hermann.
authored
1012 did not include variables defined in the template. As a matter of
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1013 fact, this did not work::
673aa88 @mitsuhiko imports and includes "with context" are passed the full context now, not...
authored
1014
1015 {% for box in boxes %}
1016 {% include "render_box.html" %}
1017 {% endfor %}
1018
02901a8 @alanhogan Clarity
alanhogan authored
1019 The included template ``render_box.html`` is *not* able to access
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1020 `box` in Jinja 2.0. As of Jinja 2.1, ``render_box.html`` *is* able
02901a8 @alanhogan Clarity
alanhogan authored
1021 to do so.
673aa88 @mitsuhiko imports and includes "with context" are passed the full context now, not...
authored
1022
ea847c5 @mitsuhiko added "with context" or "without context" import/include modifiers
authored
1023
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1024 .. _expressions:
1025
1026 Expressions
1027 -----------
1028
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1029 Jinja allows basic expressions everywhere. These work very similarly to
1030 regular Python; even if you're not working with Python
1031 you should feel comfortable with it.
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1032
1033 Literals
1034 ~~~~~~~~
1035
1036 The simplest form of expressions are literals. Literals are representations
1037 for Python objects such as strings and numbers. The following literals exist:
1038
316157d @mitsuhiko fixed another python2.4 bug
authored
1039 "Hello World":
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1040 Everything between two double or single quotes is a string. They are
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1041 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
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1043 template).
1044
316157d @mitsuhiko fixed another python2.4 bug
authored
1045 42 / 42.23:
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1046 Integers and floating point numbers are created by just writing the
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1047 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).
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1050
316157d @mitsuhiko fixed another python2.4 bug
authored
1051 ['list', 'of', 'objects']:
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1052 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::
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1055
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
316157d @mitsuhiko fixed another python2.4 bug
authored
1063 ('tuple', 'of', 'values'):
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1064 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.
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1068
ad48a2e Fixed typos in documentation
Lukas Meuser authored
1069 {'dict': 'of', 'key': 'and', 'value': 'pairs'}:
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1070 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
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1072 templates; they are useful in some rare cases such as the :func:`xmlattr`
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1073 filter.
1074
316157d @mitsuhiko fixed another python2.4 bug
authored
1075 true / false:
9bb7e47 @mitsuhiko some more documentation updates and minor code cleanups. Additionally T...
authored
1076 true is always true and false is always false.
1077
1078 .. admonition:: Note
1079
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1080 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.
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1087
1088 Math
1089 ~~~~
1090
1091 Jinja allows you to calculate with values. This is rarely useful in templates
0aa0f58 @mitsuhiko Applied documentation patches by Clemens Hermann.
authored
1092 but exists for completeness' sake. The following operators are supported:
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1093
316157d @mitsuhiko fixed another python2.4 bug
authored
1094 \+
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1095 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``.
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1099
316157d @mitsuhiko fixed another python2.4 bug
authored
1100 \-
3fc008b @jwilk fix a bunch of typos in the documentation
jwilk authored
1101 Subtract the second number from the first one. ``{{ 3 - 2 }}`` is ``1``.
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1102
316157d @mitsuhiko fixed another python2.4 bug
authored
1103 /
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1104 Divide two numbers. The return value will be a floating point number.
1105 ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``.
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1106 (Just like ``from __future__ import division``.)
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1107
316157d @mitsuhiko fixed another python2.4 bug
authored
1108 //
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1109 Divide two numbers and return the truncated integer result.
6ae1285 @fabiant7t Fixed example of a division with a truncated integer result (it's // ins...
fabiant7t authored
1110 ``{{ 20 // 7 }}`` is ``2``.
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1111
316157d @mitsuhiko fixed another python2.4 bug
authored
1112 %
0aa0f58 @mitsuhiko Applied documentation patches by Clemens Hermann.
authored
1113 Calculate the remainder of an integer division. ``{{ 11 % 7 }}`` is ``4``.
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1114
316157d @mitsuhiko fixed another python2.4 bug
authored
1115 \*
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1116 Multiply the left operand with the right one. ``{{ 2 * 2 }}`` would
0aa0f58 @mitsuhiko Applied documentation patches by Clemens Hermann.
authored
1117 return ``4``. This can also be used to repeat a string multiple times.
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1118 ``{{ '=' * 80 }}`` would print a bar of 80 equal signs.
1119
316157d @mitsuhiko fixed another python2.4 bug
authored
1120 \**
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1121 Raise the left operand to the power of the right operand. ``{{ 2**3 }}``
1122 would return ``8``.
1123
3c95532 @mitsuhiko Fixed spelling
authored
1124 Comparisons
1125 ~~~~~~~~~~~
13203e1 @mitsuhiko Added docs for comparisions
authored
1126
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
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1145 Logic
1146 ~~~~~
1147
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1148 For `if` statements, `for` filtering, and `if` expressions, it can be useful to
0aa0f58 @mitsuhiko Applied documentation patches by Clemens Hermann.
authored
1149 combine multiple expressions:
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1150
316157d @mitsuhiko fixed another python2.4 bug
authored
1151 and
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1152 Return true if the left and the right operand are true.
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1153
316157d @mitsuhiko fixed another python2.4 bug
authored
1154 or
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1155 Return true if the left or the right operand are true.
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1156
316157d @mitsuhiko fixed another python2.4 bug
authored
1157 not
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1158 negate a statement (see below).
1159
316157d @mitsuhiko fixed another python2.4 bug
authored
1160 (expr)
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1161 group an expression.
1162
9bb7e47 @mitsuhiko some more documentation updates and minor code cleanups. Additionally T...
authored
1163 .. admonition:: Note
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1164
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1165 The ``is`` and ``in`` operators support negation using an infix notation,
9bb7e47 @mitsuhiko some more documentation updates and minor code cleanups. Additionally T...
authored
1166 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).``
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1169
1170
1171 Other Operators
1172 ~~~~~~~~~~~~~~~
1173
1174 The following operators are very useful but don't fit into any of the other
1175 two categories:
1176
316157d @mitsuhiko fixed another python2.4 bug
authored
1177 in
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1178 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.
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1181
316157d @mitsuhiko fixed another python2.4 bug
authored
1182 is
1183 Performs a :ref:`test <tests>`.
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1184
316157d @mitsuhiko fixed another python2.4 bug
authored
1185 \|
1186 Applies a :ref:`filter <filters>`.
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1187
316157d @mitsuhiko fixed another python2.4 bug
authored
1188 ~
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1189 Converts all operands into strings and concatenates them.
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1190
1191 ``{{ "Hello " ~ name ~ "!" }}`` would return (assuming `name` is set
1192 to ``'John'``) ``Hello John!``.
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1193
316157d @mitsuhiko fixed another python2.4 bug
authored
1194 ()
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1195 Call a callable: ``{{ post.render() }}``. Inside of the parentheses you
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1196 can use positional arguments and keyword arguments like in Python:
1197
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1198 ``{{ post.render(user, full=true) }}``.
1199
316157d @mitsuhiko fixed another python2.4 bug
authored
1200 . / []
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1201 Get an attribute of an object. (See :ref:`variables`)
1202
1203
1204 .. _if-expression:
1205
1206 If Expression
1207 ~~~~~~~~~~~~~
1208
b2a36aa @mitsuhiko updated jinja docs
authored
1209 It is also possible to use inline `if` expressions. These are useful in some
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1210 situations. For example, you can use this to extend from one template if a
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
1211 variable is defined, otherwise from the default layout template::
b2a36aa @mitsuhiko updated jinja docs
authored
1212
1213 {% extends layout_template if layout_template is defined else 'master.html' %}
709f6e5 @mitsuhiko python2.4 compatibility and doc updates
authored
1214
d84ec46 @mitsuhiko again documentation updates fixed another python 2.4 bug. Imports are n...
authored
1215 The general syntax is ``<do something> if <something is true> else <do
1216 something else>``.
1217
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1218 The `else` part is optional. If not provided, the else block implicitly
a0e3ac0 @mitsuhiko Documented if-conditional changes.
authored
1219 evaluates into an undefined object::
1220
1221 {{ '[%s]' % page.title if page.title }}
1222
157531b @mitsuhiko more docs and fixed bug in parser that assigned lineno for ExprStmt wron...
authored
1223
3c8b7ad @mitsuhiko first version of the jinja2 docs
authored
1224 .. _builtin-filters:
1225
1226 List of Builtin Filters
1227 -----------------------
1228
1229 .. jinjafilters::
1230
1231
1232 .. _builtin-tests:
1233
1234 List of Builtin Tests
1235 ---------------------
1236
157531b @mitsuhiko more docs and fixed bug in parser that assigned lineno for ExprStmt wron...
authored
1237 .. jinjatests::
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
1238
ccae055 @mitsuhiko Various cleanups and added custom cycler.
authored
1239 .. _builtin-globals:
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
1240
1241 List of Global Functions
1242 ------------------------
1243
1244 The 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.
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1249 ``range(i, j)`` returns ``[i, i+1, i+2, ..., j-1]``;
1250 start (!) defaults to ``0``.
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
1251 When step is given, it specifies the increment (or decrement).
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1252 For example, ``range(4)`` and ``range(0, 4, 1)`` return ``[0, 1, 2, 3]``.
1253 The end point is omitted!
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
1254 These are exactly the valid indices for a list of 4 elements.
1255
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1256 This is useful to repeat a template block multiple times, e.g.
19cf9c2 @mitsuhiko small performance improvements
authored
1257 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
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
1269 .. function:: lipsum(n=5, html=True, min=20, max=100)
1270
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1271 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
7259c76 @mitsuhiko moved caching from loaders to environment and added environment overlays
authored
1274 contents for layout testing.
76c280b @mitsuhiko improved sandbox, added proper striptags and updated documentation to la...
authored
1275
ed98cac @mitsuhiko some documentation updates
authored
1276 .. function:: dict(\**items)
76c280b @mitsuhiko improved sandbox, added proper striptags and updated documentation to la...
authored
1277
1278 A convenient alternative to dict literals. ``{'foo': 'bar'}`` is the same
1279 as ``dict(foo='bar')``.
ed98cac @mitsuhiko some documentation updates
authored
1280
ccae055 @mitsuhiko Various cleanups and added custom cycler.
authored
1281 .. class:: cycler(\*items)
1282
1283 The cycler allows you to cycle among values similar to how `loop.cycle`
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1284 works. Unlike `loop.cycle`, you can use this cycler outside of
ccae055 @mitsuhiko Various cleanups and added custom cycler.
authored
1285 loops or over multiple loops.
1286
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1287 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
ccae055 @mitsuhiko Various cleanups and added custom cycler.
authored
1289 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
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1311 Goes one item ahead and returns the then-current item.
ccae055 @mitsuhiko Various cleanups and added custom cycler.
authored
1312
1313 .. attribute:: current
1314
1315 Returns the current item.
2004449 @andymckay fix typo
andymckay authored
1316
ccae055 @mitsuhiko Various cleanups and added custom cycler.
authored
1317 **new in Jinja 2.1**
1318
d34eb12 @mitsuhiko Implemented and documented "joiner"
authored
1319 .. class:: joiner(sep=', ')
1320
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1321 A tiny helper that can be used to "join" multiple sections. A joiner is
bc542b0 @kschuetz calld->called
kschuetz authored
1322 passed a string and will return that string every time it's called, except
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1323 the first time (in which case it returns an empty string). You can
d34eb12 @mitsuhiko Implemented and documented "joiner"
authored
1324 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
ed98cac @mitsuhiko some documentation updates
authored
1339
1340 Extensions
1341 ----------
1342
1343 The following sections cover the built-in Jinja2 extensions that may be
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1344 enabled by an application. An application could also provide further
1345 extensions not covered by this documentation; in which case there should
1346 be a separate document explaining said :ref:`extensions
1347 <jinja-extensions>`.
ed98cac @mitsuhiko some documentation updates
authored
1348
1349 .. _i18n-in-templates:
1350
1351 i18n
1352 ~~~~
1353
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1354 If the i18n extension is enabled, it's possible to mark parts in the template
1355 as translatable. To mark a section as translatable, you can use `trans`::
ed98cac @mitsuhiko some documentation updates
authored
1356
1357 <p>{% trans %}Hello {{ user }}!{% endtrans %}</p>
1358
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1359 To translate a template expression --- say, using template filters, or by just
ed98cac @mitsuhiko some documentation updates
authored
1360 accessing an attribute of an object --- you need to bind the expression to a
1361 name for use within the translation block::
1362
1363 <p>{% trans user=user.username %}Hello {{ user }}!{% endtrans %}</p>
1364
1365 If you need to bind more than one expression inside a `trans` tag, separate
1366 the pieces with a comma (``,``)::
1367
1368 {% trans book_title=book.title, author=author.name %}
1369 This is {{ book_title }} by {{ author }}
1370 {% endtrans %}
1371
1372 Inside trans tags no statements are allowed, only variable tags are.
1373
1374 To pluralize, specify both the singular and plural forms with the `pluralize`
1375 tag, 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
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1383 By default, the first variable in a block is used to determine the correct
1384 singular or plural form. If that doesn't work out, you can specify the name
ed98cac @mitsuhiko some documentation updates
authored
1385 which 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
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1390 It's also possible to translate strings in expressions. For that purpose,
ed98cac @mitsuhiko some documentation updates
authored
1391 three functions exist:
1392
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1393 - `gettext`: translate a single string
ed98cac @mitsuhiko some documentation updates
authored
1394 - `ngettext`: translate a pluralizable string
1395 - `_`: alias for `gettext`
1396
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1397 For example, you can easily print a translated string like this::
ed98cac @mitsuhiko some documentation updates
authored
1398
1399 {{ _('Hello World!') }}
1400
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1401 To use placeholders, use the `format` filter::
ed98cac @mitsuhiko some documentation updates
authored
1402
1403 {{ _('Hello %(user)s!')|format(user=user.username) }}
1404
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1405 For multiple placeholders, always use keyword arguments to `format`,
1406 as other languages may not use the words in the same order.
5d2733f @mitsuhiko void -> do
authored
1407
ffaa2e7 @mitsuhiko it's now possible to register extensions after an environment
authored
1408 .. versionchanged:: 2.5
1409
8a3d93b @mitsuhiko Fixed a typo in the docs
authored
1410 If newstyle gettext calls are activated (:ref:`newstyle-gettext`), using
ffaa2e7 @mitsuhiko it's now possible to register extensions after an environment
authored
1411 placeholders 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
522af5d @kschuetz recieves->receives
kschuetz authored
1419 Note that the `ngettext` function's format string automatically receives
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1420 the count as a `num` parameter in addition to the regular parameters.
ffaa2e7 @mitsuhiko it's now possible to register extensions after an environment
authored
1421
5d2733f @mitsuhiko void -> do
authored
1422
61a5a24 @mitsuhiko fixed a bug in error reporting and some small documentation updates
authored
1423 Expression Statement
1424 ~~~~~~~~~~~~~~~~~~~~
5d2733f @mitsuhiko void -> do
authored
1425
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1426 If the expression-statement extension is loaded, a tag called `do` is available
1427 that works exactly like the regular variable expression (``{{ ... }}``); except
1428 it doesn't print anything. This can be used to modify lists::
5d2733f @mitsuhiko void -> do
authored
1429
1430 {% do navigation.append('a string') %}
3da9031 @mitsuhiko added loopcontrols extension and added unittests for it
authored
1431
1432
1433 Loop Controls
1434 ~~~~~~~~~~~~~
1435
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1436 If the application enables the :ref:`loopcontrols-extension`, it's possible to
3da9031 @mitsuhiko added loopcontrols extension and added unittests for it
authored
1437 use `break` and `continue` in loops. When `break` is reached, the loop is
c585550 @kschuetz added comma
kschuetz authored
1438 terminated; if `continue` is reached, the processing is stopped and continues
3da9031 @mitsuhiko added loopcontrols extension and added unittests for it
authored
1439 with the next iteration.
1440
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1441 Here's a loop that skips every second item::
3da9031 @mitsuhiko added loopcontrols extension and added unittests for it
authored
1442
1443 {% for user in users %}
1444 {%- if loop.index is even %}{% continue %}{% endif %}
1445 ...
1446 {% endfor %}
1447
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1448 Likewise, a loop that stops processing after the 10th iteration::
3da9031 @mitsuhiko added loopcontrols extension and added unittests for it
authored
1449
1450 {% for user in users %}
1451 {%- if loop.index >= 10 %}{% break %}{% endif %}
1452 {%- endfor %}
9b4cc9f @mitsuhiko added with-statement extension.
authored
1453
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1454 Note that ``loop.index`` starts with 1, and ``loop.index0`` starts with 0
1455 (See: :ref:`for-loop`).
1456
9b4cc9f @mitsuhiko added with-statement extension.
authored
1457
1458 With Statement
1459 ~~~~~~~~~~~~~~
1460
1461 .. versionadded:: 2.3
1462
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1463 If the application enables the :ref:`with-extension`, it is possible to
9b4cc9f @mitsuhiko added with-statement extension.
authored
1464 use the `with` keyword in templates. This makes it possible to create
1465 a new inner scope. Variables set within this scope are not visible
1466 outside of the scope.
1467
1468 With 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
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1476 Because it is common to set variables at the beginning of the scope,
1477 you can do that within the `with` statement. The following two examples
9b4cc9f @mitsuhiko added with-statement extension.
authored
1478 are equivalent::
1479
1480 {% with foo = 42 %}
1481 {{ foo }}
1482 {% endwith %}
1483
1484 {% with %}
1485 {% set foo = 42 %}
1486 {{ foo }}
1487 {% endwith %}
fe150f3 @mitsuhiko Documented autoescaping behavior and eval contexts.
authored
1488
752ba7f @mitsuhiko Added missing reference.
authored
1489 .. _autoescape-overrides:
fe150f3 @mitsuhiko Documented autoescaping behavior and eval contexts.
authored
1490
1491 Autoescape Extension
1492 --------------------
1493
1494 .. versionadded:: 2.4
1495
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1496 If the application enables the :ref:`autoescape-extension`, one can
fe150f3 @mitsuhiko Documented autoescaping behavior and eval contexts.
authored
1497 activate and deactivate the autoescaping from within the templates.
1498
1499 Example::
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
d40e9ba @westurner DOC: Update templates.rst: syntax, commas
westurner authored
1509 After an `endautoescape` the behavior is reverted to what it was before.
Something went wrong with that request. Please try again.