1 Template Designer Documentation
2 ===============================
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
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.
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.
22 Below is a minimal template that illustrates a few basics. We will cover
23 the details later in that document:
25 .. sourcecode:: html+jinja
27 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
30 <title>My Webpage</title>
34 {% for item in navigation %}
35 <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
44 This covers the default settings. The application developer might have
45 changed the syntax from ``{% foo %}`` to ``<% foo %>`` or something similar.
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.
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
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
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
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.
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
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(', ') }}``.
94 The :ref:`builtin-filters` below describes all the builtin filters.
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.
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:
111 .. sourcecode:: jinja
113 {% if loop.index is divisibleby 3 %}
114 {% if loop.index is divisibleby(3) %}
116 The :ref:`builtin-tests` below descibes all the builtin tests.
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
127 .. sourcecode:: jinja
129 {# note: disabled template because we no longer user this
130 {% for user in users %}
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.
143 Sounds complicated but is very basic. It's easiest to understand it by starting
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:
154 .. sourcecode:: html+jinja
156 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
158 <html xmlns="http://www.w3.org/1999/xhtml">
161 <link rel="stylesheet" href="style.css" />
162 <title>{% block title %}{% endblock %} - My Webpage</title>
166 <div id="content">{% block content %}{% endblock %}</div>
169 © Copyright 2008 by <a href="http://domain.invalid/">you</a>.
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.
181 A child template might look like this:
183 .. sourcecode:: html+jinja
185 {% extends "base.html" %}
186 {% block title %}Index{% endblock %}
189 <style type="text/css">
190 .important { color: #336699; }
195 <p class="important">
196 Welcome on my awsome homepage.
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
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:
210 .. sourcecode:: jinja
212 {% extends "layout/default.html" %}
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.
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.
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:
228 .. sourcecode:: jinja
230 <title>{% block title %}{% endblock %}</title>
231 <h1>{{ self.title() }}</h1>
232 {% block body %}{% endblock %}
235 Unlike Python Jinja does not support multiple inheritance. So you can only have
236 one extends tag called per rendering.
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:
245 .. sourcecode:: jinja
248 <h3>Table Of Contents</h3>
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.
261 Jinja supports both, but what is used depends on the application configuration.
262 The default configuaration is no automatic escaping for various reasons:
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.
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
272 Working with Manual Escaping
273 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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 }}``.
282 Working with Automatic Escaping
283 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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.
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
297 Functions returning template data (macros, `super`, `self.BLOCKNAME`) return
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.
305 List of Control Structures
306 --------------------------
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.
316 Loop over each item in a sequece. For example, to display a list of users
317 provided in a variable called `users`:
319 .. sourcecode:: html+jinja
323 {% for user in users %}
324 <li>{{ user.username|e }}</li>
328 Inside of a for loop block you can access some special variables:
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 |
339 +-----------------------+---------------------------------------------------+
340 | `loop.revindex0` | The number of iterations from the end of the loop |
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 +-----------------------+---------------------------------------------------+
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:
356 .. sourcecode:: html+jinja
358 {% for row in rows %}
359 <li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>
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:
368 .. sourcecode:: html+jinja
370 {% for user in users if not user.hidden %}
371 <li>{{ user.username|e }}</li>
374 The advantage is that the special `loop` variable will count correctly thus
375 not counting the users not iterated over.
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
381 .. sourcecode:: html+jinja
384 {% for user in users %}
385 <li>{{ user.username|e }}</li>
387 <li><em>no users found</em></li>
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
399 .. sourcecode:: html+jinja
403 {% for user in users %}
404 <li>{{ user.username|e }}</li>
409 For multiple branches `elif` and `else` can be used like in Python. You can
410 use more complex :ref:`expressions` there too.
412 .. sourcecode:: html+jinja
416 {% elif kenny.dead %}
417 You killed Kenny! You bastard!!!
419 Kenny looks okay --- so far
422 If can also be used as :ref:`inline expression <if-expression>` and for
423 :ref:`loop filtering <loop-filtering>`.
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
438 The simplest form of expressions are literals. Literals are representations
439 for Python objects such as strings and numbers. The following literals exist:
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
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
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.
458 .. sourcecode:: html+jinja
461 {% for href, caption in [('index.html', 'Index'), ('about.html', 'About'),
462 ('downloads.html', 'Downloads')] %}
463 <li><a href="{{ href }}">{{ caption }}</a></li>
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
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`
480 true is always true and false is always false. Keep in mind that those
481 literals are lowercase!
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:
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``.
496 Substract two numbers from each other. ``{{ 3 - 2 }}`` is ``1``.
499 Divide two numbers. The return value will be a floating point number.
500 ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``.
503 Divide two numbers and return the truncated integer result.
504 ``{{ 20 / 7 }}`` is ``2``.
507 Calculate the remainder of an integer division between the left and right
508 operand. ``{{ 11 % 7 }}`` is ``4``.
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.
516 Raise the left operand to the power of the right operand. ``{{ 2**3 }}``
522 For `if` statements / `for` filtering or `if` expressions it can be useful to
523 combine group multiple expressions:
526 Return true if the left and the right operand is true.
529 Return true if the left or the right operand is true.
532 negate a statement (see below).
537 Note that there is no support for any bit operations or something similar.
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).``
548 The following operators are very useful but don't fit into any of the other
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
557 Performs a :ref:`test <tests>`.
560 Applies a :ref:`filter <filters>`.
563 Converts all operands into strings and concatenates them.
564 ``{{ "Hello " ~ name ~ "!" }}`` would return (assuming `name` is
565 ``'John'``) ``Hello John!``.
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) }}``.
573 Get an attribute of an object. (See :ref:`variables`)
581 It is also possible to use inline `if` expressions. These are useful in some
582 situations. For example you can use this to extend from one template if a
583 variable is defined, otherwise from the default layout template:
585 .. sourcecode:: jinja
587 {% extends layout_template if layout_template is defined else 'master.html' %}
592 List of Builtin Filters
593 -----------------------
600 List of Builtin Tests
601 ---------------------