fixed another python2.4 bug
[jinja2.git] / docs / templates.rst
1 Template Designer Documentation
2 ===============================
3
4 This document describes the syntax and semantics of the template engine and
5 will be most useful as reference to those creating Jinja templates.  As the
6 template engine is very flexible the configuration from the application might
7 be slightly different from here in terms of delimiters and behavior of
8 undefined values.
9
10
11 Synopsis
12 --------
13
14 A template is simply a text file.  It can generate any text-based format
15 (HTML, XML, CSV, LaTeX, etc.).  It doesn't have a specific extension,
16 ``.html`` or ``.xml`` are just fine.
17
18 A template contains **variables** or **expressions**, which get replaced with
19 values when the template is evaluated, and tags, which control the logic of
20 the template.  The template syntax is heavily inspired by Django and Python.
21
22 Below is a minimal template that illustrates a few basics.  We will cover
23 the details later in that document:
24
25 .. sourcecode:: html+jinja
26
27     <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
28     <html lang="en">
29     <head>
30         <title>My Webpage</title>
31     </head>
32     <body>
33         <ul id="navigation">
34         {% for item in navigation %}
35             <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
36         {% endfor %}
37         </ul>
38
39         <h1>My Webpage</h1>
40         {{ a_variable }}
41     </body>
42     </html>
43
44 This covers the default settings.  The application developer might have
45 changed the syntax from ``{% foo %}`` to ``<% foo %>`` or something similar.
46
47 There are two kinds of delimiers. ``{% ... %}`` and ``{{ ... }}``.  The first
48 one is used to execute statements such as for-loops or assign values, the
49 latter prints the result of the expression to the template.
50
51 .. _variables:
52
53 Variables
54 ---------
55
56 The application passes variables to the templates you can mess around in the
57 template.  Variables may have attributes or elements on them you can access
58 too.  How a variable looks like, heavily depends on the application providing
59 those.
60
61 You can use a dot (``.``) to access attributes of a variable, alternative the
62 so-called "subscribe" syntax (``[]``) can be used.  The following lines do
63 the same:
64
65 .. sourcecode:: jinja
66
67     {{ foo.bar }}
68     {{ foo['bar'] }}
69
70 It's important to know that the curly braces are *not* part of the variable
71 but the print statement.  If you access variables inside tags don't put the
72 braces around.
73
74 If a variable or attribute does not exist you will get back an undefined
75 value.  What you can do with that kind of value depends on the application
76 configuration, the default behavior is that it evaluates to an empty string
77 if printed and that you can iterate over it, but every other operation fails.
78
79 .. _filters:
80
81 Filters
82 -------
83
84 Variables can by modified by **filters**.  Filters are separated from the
85 variable by a pipe symbol (``|``) and may have optional arguments in
86 parentheses.  Multiple filters can be chained.  The output of one filter is
87 applied to the next.
88
89 ``{{ name|striptags|title }}`` for example will remove all HTML Tags from the
90 `name` and title-cases it.  Filters that accept arguments have parentheses
91 around the arguments, like a function call.  This example will join a list
92 by spaces:  ``{{ list|join(', ') }}``.
93
94 The :ref:`builtin-filters` below describes all the builtin filters.
95
96 .. _tests:
97
98 Tests
99 -----
100
101 Beside filters there are also so called "tests" available.  Tests can be used
102 to test a variable against a common expression.  To test a variable or
103 expression you add `is` plus the name of the test after the variable.  For
104 example to find out if a variable is defined you can do ``name is defined``
105 which will then return true or false depening on if `name` is defined.
106
107 Tests can accept arguments too.  If the test only takes one argument you can
108 leave out the parentheses to group them.  For example the following two
109 expressions do the same:
110
111 .. sourcecode:: jinja
112
113     {% if loop.index is divisibleby 3 %}
114     {% if loop.index is divisibleby(3) %}
115
116 The :ref:`builtin-tests` below descibes all the builtin tests.
117
118
119 Comments
120 --------
121
122 To comment-out part of a line in a template, use the comment syntax which is
123 by default set to ``{# ... #}``.  This is useful to comment out parts of the
124 template for debugging or to add information for other template designers or
125 yourself:
126
127 .. sourcecode:: jinja
128
129     {# note: disabled template because we no longer user this
130         {% for user in users %}
131             ...
132         {% endfor %}
133     #}
134
135
136 Template Inheritance
137 --------------------
138
139 The most powerful part of Jinja is template inheritance. Template inheritance
140 allows you to build a base "skeleton" template that contains all the common
141 elements of your site and defines **blocks** that child templates can override.
142
143 Sounds complicated but is very basic. It's easiest to understand it by starting
144 with an example.
145
146
147 Base Template
148 ~~~~~~~~~~~~~
149
150 This template, which we'll call ``base.html``, defines a simple HTML skeleton
151 document that you might use for a simple two-column page. It's the job of
152 "child" templates to fill the empty blocks with content:
153
154 .. sourcecode:: html+jinja
155
156     <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
157     <html lang="en">
158     <html xmlns="http://www.w3.org/1999/xhtml">
159     <head>
160         {% block head %}
161         <link rel="stylesheet" href="style.css" />
162         <title>{% block title %}{% endblock %} - My Webpage</title>
163         {% endblock %}
164     </head>
165     <body>
166         <div id="content">{% block content %}{% endblock %}</div>
167         <div id="footer">
168             {% block footer %}
169             &copy; Copyright 2008 by <a href="http://domain.invalid/">you</a>.
170             {% endblock %}
171         </div>
172     </body>
173
174 In this example, the ``{% block %}`` tags define four blocks that child templates
175 can fill in. All the `block` tag does is to tell the template engine that a
176 child template may override those portions of the template.
177
178 Child Template
179 ~~~~~~~~~~~~~~
180
181 A child template might look like this:
182
183 .. sourcecode:: html+jinja
184
185     {% extends "base.html" %}
186     {% block title %}Index{% endblock %}
187     {% block head %}
188         {{ super() }}
189         <style type="text/css">
190             .important { color: #336699; }
191         </style>
192     {% endblock %}
193     {% block content %}
194         <h1>Index</h1>
195         <p class="important">
196           Welcome on my awsome homepage.
197         </p>
198     {% endblock %}
199
200 The ``{% extends %}`` tag is the key here. It tells the template engine that
201 this template "extends" another template.  When the template system evaluates
202 this template, first it locates the parent.  The extends tag should be the
203 first tag in the template.  Everything before it is printed out normally and
204 may cause confusion.
205
206 The filename of the template depends on the template loader.  For example the
207 :class:`FileSystemLoader` allows you to access other templates by giving the
208 filename.  You can access templates in subdirectories with an slash:
209
210 .. sourcecode:: jinja
211
212     {% extends "layout/default.html" %}
213
214 But this behavior can depend on the application embedding Jinja.  Note that
215 since the child template doesn't define the ``footer`` block, the value from
216 the parent template is used instead.
217
218 You can't define multiple ``{% block %}`` tags with the same name in the
219 same template.  This limitation exists because a block tag works in "both"
220 directions.  That is, a block tag doesn't just provide a hole to fill - it
221 also defines the content that fills the hole in the *parent*.  If there
222 were two similarly-named ``{% block %}`` tags in a template, that template's
223 parent wouldn't know which one of the blocks' content to use.
224
225 If you want to print a block multiple times you can however use the special
226 `self` variable and call the block with that name:
227
228 .. sourcecode:: jinja
229
230     <title>{% block title %}{% endblock %}</title>
231     <h1>{{ self.title() }}</h1>
232     {% block body %}{% endblock %}
233
234
235 Unlike Python Jinja does not support multiple inheritance.  So you can only have
236 one extends tag called per rendering.
237
238
239 Super Blocks
240 ~~~~~~~~~~~~
241
242 It's possible to render the contents of the parent block by calling `super`.
243 This gives back the results of the parent block:
244
245 .. sourcecode:: jinja
246
247     {% block sidebar %}
248         <h3>Table Of Contents</h3>
249         ...
250         {{ super() }}
251     {% endblock %}
252
253
254 HTML Escaping
255 -------------
256
257 When generating HTML from templates, there's always a risk that a variable will
258 include characters that affect the resulting HTML.  There are two approaches:
259 manually escaping each variable or automatically escaping everything by default.
260
261 Jinja supports both, but what is used depends on the application configuration.
262 The default configuaration is no automatic escaping for various reasons:
263
264 -   escaping everything except of safe values will also mean that Jinja is
265     escaping variables known to not include HTML such as numbers which is
266     a huge performance hit.
267
268 -   The information about the safety of a variable is very fragile.  It could
269     happen that by coercing safe and unsafe values the return value is double
270     escaped HTML.
271
272 Working with Manual Escaping
273 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
274
275 If manual escaping is enabled it's **your** responsibility to escape
276 variables if needed.  What to escape?  If you have a variable that *may*
277 include any of the following chars (``>``, ``<``, ``&``, or ``"``) you
278 **have to** escape it unless the variable contains well-formed and trusted
279 HTML.  Escaping works by piping the variable through the ``|e`` filter:
280 ``{{ user.username|e }}``.
281
282 Working with Automatic Escaping
283 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
284
285 When automatic escaping is enabled everything is escaped by default except
286 for values explicitly marked as safe.  Those can either be marked by the
287 application or in the template by using the `|safe` filter.  The main
288 problem with this approach is that Python itself doesn't have the concept
289 of tainted values so the information if a value is safe or unsafe can get
290 lost.  If the information is lost escaping will take place which means that
291 you could end up with double escaped contents.
292
293 Double escaping is easy to avoid however, just relay on the tools Jinja2
294 provides and don't use builtin Python constructs such as the string modulo
295 operator.
296
297 Functions returning template data (macros, `super`, `self.BLOCKNAME`) return
298 safe markup always.
299
300 String literals in templates with automatic escaping are considered unsafe
301 too.  The reason for this is that the safe string is an extension to Python
302 and not every library will work properly with it.
303
304
305 List of Control Structures
306 --------------------------
307
308 A control structure refers to all those things that control the flow of a
309 program - conditionals (i.e. if/elif/else), for-loops, as well as things like
310 macros and blocks.  Control structures appear inside ``{% ... %}`` blocks
311 in the default syntax.
312
313 For Loops
314 ~~~~~~~~~
315
316 Loop over each item in a sequece.  For example, to display a list of users
317 provided in a variable called `users`:
318
319 .. sourcecode:: html+jinja
320
321     <h1>Members</h1>
322     <ul>
323     {% for user in users %}
324       <li>{{ user.username|e }}</li>
325     {% endfor %}
326     </ul>
327
328 Inside of a for loop block you can access some special variables:
329
330 +-----------------------+---------------------------------------------------+
331 | Variable              | Description                                       |
332 +=======================+===================================================+
333 | `loop.index`          | The current iteration of the loop. (1 indexed)    |
334 +-----------------------+---------------------------------------------------+
335 | `loop.index0`         | The current iteration of the loop. (0 indexed)    |
336 +-----------------------+---------------------------------------------------+
337 | `loop.revindex`       | The number of iterations from the end of the loop |
338 |                       | (1 indexed)                                       |
339 +-----------------------+---------------------------------------------------+
340 | `loop.revindex0`      | The number of iterations from the end of the loop |
341 |                       | (0 indexed)                                       |
342 +-----------------------+---------------------------------------------------+
343 | `loop.first`          | True if first iteration.                          |
344 +-----------------------+---------------------------------------------------+
345 | `loop.last`           | True if last iteration.                           |
346 +-----------------------+---------------------------------------------------+
347 | `loop.length`         | The number of items in the sequence.              |
348 +-----------------------+---------------------------------------------------+
349 | `loop.cycle`          | A helper function to cycle between a list of      |
350 |                       | sequences.  See the explanation below.            |
351 +-----------------------+---------------------------------------------------+
352
353 Within a for-loop, it's psosible to cycle among a list of strings/variables
354 each time through the loop by using the special `loop.cycle` helper:
355
356 .. sourcecode:: html+jinja
357
358     {% for row in rows %}
359         <li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>
360     {% endfor %}
361
362 .. _loop-filtering:
363
364 Unlike in Python it's not possible to `break` or `continue` in a loop.  You
365 can however filter the sequence during iteration which allows you to skip
366 items.  The following example skips all the users which are hidden:
367
368 .. sourcecode:: html+jinja
369
370     {% for user in users if not user.hidden %}
371         <li>{{ user.username|e }}</li>
372     {% endfor %}
373
374 The advantage is that the special `loop` variable will count correctly thus
375 not counting the users not iterated over.
376
377 If no iteration took place because the sequence was empty or the filtering
378 removed all the items from the sequence you can render a replacement block
379 by using `else`:
380
381 .. sourcecode:: html+jinja
382
383     <ul>
384     {% for user in users %}
385         <li>{{ user.username|e }}</li>
386     {% else %}
387         <li><em>no users found</em></li>
388     {% endif %}
389     </ul>
390
391
392 If
393 ~~
394
395 The `if` statement in Jinja is comparable with the if statements of Python.
396 In the simplest form you can use it to test if a variable is defined, not
397 empty or not false:
398
399 .. sourcecode:: html+jinja
400
401     {% if users %}
402     <ul>
403     {% for user in users %}
404         <li>{{ user.username|e }}</li>
405     {% endfor %}
406     </ul>
407     {% endif %}
408
409 For multiple branches `elif` and `else` can be used like in Python.  You can
410 use more complex :ref:`expressions` there too.
411
412 .. sourcecode:: html+jinja
413
414     {% if kenny.sick %}
415         Kenny is sick.
416     {% elif kenny.dead %}
417         You killed Kenny!  You bastard!!!
418     {% else %}
419         Kenny looks okay --- so far
420     {% endif %}
421
422 If can also be used as :ref:`inline expression <if-expression>` and for
423 :ref:`loop filtering <loop-filtering>`.
424
425
426 .. _expressions:
427
428 Expressions
429 -----------
430
431 Jinja allows basic expressions everywhere.  These work very similar to regular
432 Python and even if you're not working with Python you should feel comfortable
433 with it.
434
435 Literals
436 ~~~~~~~~
437
438 The simplest form of expressions are literals.  Literals are representations
439 for Python objects such as strings and numbers.  The following literals exist:
440
441 "Hello World":
442     Everything between two double or single quotes is a string.  They are
443     useful whenever you need a string in the template (for example as
444     arguments to function calls, filters or just to extend or include a
445     template).
446
447 42 / 42.23:
448     Integers and floating point numbers are created by just writing the
449     number down.  If a dot is present the number is a float, otherwise an
450     integer.  Keep in mind that for Python ``42`` and ``42.0`` is something
451     different.
452
453 ['list', 'of', 'objects']:
454     Everything between two brackets is a list.  Lists are useful to store
455     sequential data in or to iterate over them.  For example you can easily
456     create a list of links using lists and tuples with a for loop.
457
458     .. sourcecode:: html+jinja
459
460         <ul>
461         {% for href, caption in [('index.html', 'Index'), ('about.html', 'About'),
462                                  ('downloads.html', 'Downloads')] %}
463             <li><a href="{{ href }}">{{ caption }}</a></li>
464         {% endfor %}
465         </ul>
466
467 ('tuple', 'of', 'values'):
468     Tuples are like lists, just that you can't modify them.  If the tuple
469     only has one item you have to end it with a comma.  Tuples are usually
470     used to represent items of two or more elements.  See the example above
471     for more details.
472
473 {'dict': 'of', 'keys': 'and', 'value': 'pairs'}:
474     A dict in Python is a structure that combines keys and values.  Keys must
475     be unique and always have exactly one value.  Dicts are rarely used in
476     templates, they are useful in some rare cases such as the :func:`xmlattr`
477     filter.
478
479 true / false:
480     true is always true and false is always false.  Keep in mind that those
481     literals are lowercase!
482
483 Math
484 ~~~~
485
486 Jinja allows you to calculate with values.  This is rarely useful in templates
487 but exists for completeness sake.  The following operators are supported:
488
489 \+
490     Adds two objects with each other.  Usually numbers but if both objects are
491     strings or lists you can concatenate them this way.  This however is not
492     the preferred way to concatenate strings!  For string concatenation have
493     a look at the ``~`` operator.  ``{{ 1 + 1 }}`` is ``2``.
494
495 \-
496     Substract two numbers from each other.  ``{{ 3 - 2 }}`` is ``1``.
497
498 /
499     Divide two numbers.  The return value will be a floating point number.
500     ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``.
501
502 //
503     Divide two numbers and return the truncated integer result.
504     ``{{ 20 / 7 }}`` is ``2``.
505
506 %
507     Calculate the remainder of an integer division between the left and right
508     operand.  ``{{ 11 % 7 }}`` is ``4``.
509
510 \*
511     Multiply the left operand with the right one.  ``{{ 2 * 2 }}`` would
512     return ``4``.  This can also be used to repeat string multiple times.
513     ``{{ '=' * 80 }}`` would print a bar of 80 equal signs.
514
515 \**
516     Raise the left operand to the power of the right operand.  ``{{ 2**3 }}``
517     would return ``8``.
518
519 Logic
520 ~~~~~
521
522 For `if` statements / `for` filtering or `if` expressions it can be useful to
523 combine group multiple expressions:
524
525 and
526     Return true if the left and the right operand is true.
527
528 or
529     Return true if the left or the right operand is true.
530
531 not
532     negate a statement (see below).
533
534 (expr)
535     group an expression.
536
537 Note that there is no support for any bit operations or something similar.
538
539 -   special note regarding ``not``: The ``is`` and ``in`` operators support
540     negation using an infix notation too: ``foo is not bar`` and
541     ``foo not in bar`` instead of ``not foo is bar`` and ``not foo in bar``.
542     All other expressions require a prefix notation: ``not (foo and bar).``
543
544
545 Other Operators
546 ~~~~~~~~~~~~~~~
547
548 The following operators are very useful but don't fit into any of the other
549 two categories:
550
551 in
552     Perform sequence / mapping containment test.  Returns true if the left
553     operand is contained in the right.  ``{{ 1 in [1, 2, 3] }}`` would for
554     example return true.
555
556 is
557     Performs a :ref:`test <tests>`.
558
559 \|
560     Applies a :ref:`filter <filters>`.
561
562 ~
563     Converts all operands into strings and concatenates them.
564     ``{{ "Hello " ~ name ~ "!" }}`` would return (assuming `name` is
565     ``'John'``) ``Hello John!``.
566
567 ()
568     Call a callable: ``{{ post.render() }}``.  Inside of the parentheses you
569     can use arguments and keyword arguments like in python:
570     ``{{ post.render(user, full=true) }}``.
571
572 . / []
573     Get an attribute of an object.  (See :ref:`variables`)
574
575
576 .. _if-expression:
577
578 If Expression
579 ~~~~~~~~~~~~~
580
581 blah
582
583
584 .. _builtin-filters:
585
586 List of Builtin Filters
587 -----------------------
588
589 .. jinjafilters::
590
591
592 .. _builtin-tests:
593
594 List of Builtin Tests
595 ---------------------
596
597 .. jinjatests::