first version of the jinja2 docs
[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
52 Variables
53 ---------
54
55 The application passes variables to the templates you can mess around in the
56 template.  Variables may have attributes or elements on them you can access
57 too.  How a variable looks like, heavily depends on the application providing
58 those.
59
60 You can use a dot (``.``) to access attributes of a variable, alternative the
61 so-called "subscribe" syntax (``[]``) can be used.  The following lines do
62 the same:
63
64 .. sourcecode:: jinja
65
66     {{ foo.bar }}
67     {{ foo['bar'] }}
68
69 It's important to know that the curly braces are *not* part of the variable
70 but the print statement.  If you access variables inside tags don't put the
71 braces around.
72
73 If a variable or attribute does not exist you will get back an undefined
74 value.  What you can do with that kind of value depends on the application
75 configuration, the default behavior is that it evaluates to an empty string
76 if printed and that you can iterate over it, but every other operation fails.
77
78
79 Filters
80 -------
81
82 Variables can by modified by **filters**.  Filters are separated from the
83 variable by a pipe symbol (``|``) and may have optional arguments in
84 parentheses.  Multiple filters can be chained.  The output of one filter is
85 applied to the next.
86
87 ``{{ name|striptags|title }}`` for example will remove all HTML Tags from the
88 `name` and title-cases it.  Filters that accept arguments have parentheses
89 around the arguments, like a function call.  This example will join a list
90 by spaces:  ``{{ list|join(', ') }}``.
91
92 The `builtin-filters`_ below describes all the builtin filters.
93
94
95 Tests
96 -----
97
98 Beside filters there are also so called "tests" available.  Tests can be used
99 to test a variable against a common expression.  To test a variable or
100 expression you add `is` plus the name of the test after the variable.  For
101 example to find out if a variable is defined you can do ``name is defined``
102 which will then return true or false depening on if `name` is defined.
103
104 Tests can accept arguments too.  If the test only takes one argument you can
105 leave out the parentheses to group them.  For example the following two
106 expressions do the same:
107
108 .. sourcecode:: jinja
109
110     {% if loop.index is divisibleby 3 %}
111     {% if loop.index is divisibleby(3) %}
112
113 The `builtin-tests`_ below descibes all the builtin tests.
114
115
116 Comments
117 --------
118
119 To comment-out part of a line in a template, use the comment syntax which is
120 by default set to ``{# ... #}``.  This is useful to comment out parts of the
121 template for debugging or to add information for other template designers or
122 yourself:
123
124 .. sourcecode:: jinja
125
126     {# note: disabled template because we no longer user this
127         {% for user in users %}
128             ...
129         {% endfor %}
130     #}
131
132
133 Template Inheritance
134 --------------------
135
136 The most powerful part of Jinja is template inheritance. Template inheritance
137 allows you to build a base "skeleton" template that contains all the common
138 elements of your site and defines **blocks** that child templates can override.
139
140 Sounds complicated but is very basic. It's easiest to understand it by starting
141 with an example.
142
143
144 Base Template
145 ~~~~~~~~~~~~~
146
147 This template, which we'll call ``base.html``, defines a simple HTML skeleton
148 document that you might use for a simple two-column page. It's the job of
149 "child" templates to fill the empty blocks with content:
150
151 .. sourcecode:: html+jinja
152
153     <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
154     <html lang="en">
155     <html xmlns="http://www.w3.org/1999/xhtml">
156     <head>
157         {% block head %}
158         <link rel="stylesheet" href="style.css" />
159         <title>{% block title %}{% endblock %} - My Webpage</title>
160         {% endblock %}
161     </head>
162     <body>
163         <div id="content">{% block content %}{% endblock %}</div>
164         <div id="footer">
165             {% block footer %}
166             &copy; Copyright 2008 by <a href="http://domain.invalid/">you</a>.
167             {% endblock %}
168         </div>
169     </body>
170
171 In this example, the ``{% block %}`` tags define four blocks that child templates
172 can fill in. All the `block` tag does is to tell the template engine that a
173 child template may override those portions of the template.
174
175 Child Template
176 ~~~~~~~~~~~~~~
177
178 A child template might look like this:
179
180 .. sourcecode:: html+jinja
181
182     {% extends "base.html" %}
183     {% block title %}Index{% endblock %}
184     {% block head %}
185         {{ super() }}
186         <style type="text/css">
187             .important { color: #336699; }
188         </style>
189     {% endblock %}
190     {% block content %}
191         <h1>Index</h1>
192         <p class="important">
193           Welcome on my awsome homepage.
194         </p>
195     {% endblock %}
196
197 The ``{% extends %}`` tag is the key here. It tells the template engine that
198 this template "extends" another template.  When the template system evaluates
199 this template, first it locates the parent.  The extends tag should be the
200 first tag in the template.  Everything before it is printed out normally and
201 may cause confusion.
202
203 The filename of the template depends on the template loader.  For example the
204 :class:`FileSystemLoader` allows you to access other templates by giving the
205 filename.  You can access templates in subdirectories with an slash:
206
207 .. sourcecode:: jinja
208
209     {% extends "layout/default.html" %}
210
211 But this behavior can depend on the application embedding Jinja.  Note that
212 since the child template doesn't define the ``footer`` block, the value from
213 the parent template is used instead.
214
215 You can't define multiple ``{% block %}`` tags with the same name in the
216 same template.  This limitation exists because a block tag works in "both"
217 directions.  That is, a block tag doesn't just provide a hole to fill - it
218 also defines the content that fills the hole in the *parent*.  If there
219 were two similarly-named ``{% block %}`` tags in a template, that template's
220 parent wouldn't know which one of the blocks' content to use.
221
222 If you want to print a block multiple times you can however use the special
223 `self` variable and call the block with that name:
224
225 .. sourcecode:: jinja
226
227     <title>{% block title %}{% endblock %}</title>
228     <h1>{{ self.title() }}</h1>
229     {% block body %}{% endblock %}
230
231
232 Unlike Python Jinja does not support multiple inheritance.  So you can only have
233 one extends tag called per rendering.
234
235
236 Super Blocks
237 ~~~~~~~~~~~~
238
239 It's possible to render the contents of the parent block by calling `super`.
240 This gives back the results of the parent block:
241
242 .. sourcecode:: jinja
243
244     {% block sidebar %}
245         <h3>Table Of Contents</h3>
246         ...
247         {{ super() }}
248     {% endblock %}
249
250
251 HTML Escaping
252 -------------
253
254 When generating HTML from templates, there's always a risk that a variable will
255 include characters that affect the resulting HTML.  There are two approaches:
256 manually escaping each variable or automatically escaping everything by default.
257
258 Jinja supports both, but what is used depends on the application configuration.
259 The default configuaration is no automatic escaping for various reasons:
260
261 -   escaping everything except of safe values will also mean that Jinja is
262     escaping variables known to not include HTML such as numbers which is
263     a huge performance hit.
264
265 -   The information about the safety of a variable is very fragile.  It could
266     happen that by coercing safe and unsafe values the return value is double
267     escaped HTML.
268
269 Working with Manual Escaping
270 ----------------------------
271
272 If manual escaping is enabled it's **your** responsibility to escape
273 variables if needed.  What to escape?  If you have a variable that *may*
274 include any of the following chars (``>``, ``<``, ``&``, or ``"``) you
275 **have to** escape it unless the variable contains well-formed and trusted
276 HTML.  Escaping works by piping the variable through the ``|e`` filter:
277 ``{{ user.username|e }}``.
278
279 Working with Automatic Escaping
280 -------------------------------
281
282 When automatic escaping is enabled everything is escaped by default except
283 for values explicitly marked as safe.  Those can either be marked by the
284 application or in the template by using the `|safe` filter.  The main
285 problem with this approach is that python itself doesn't have the concept
286 of tainted values so the information if a value is safe or unsafe can get
287 lost.  If the information is lost escaping will take place which means that
288 you could end up with double escaped contents.
289
290 Double escaping is easy to avoid however, just relay on the tools Jinja2
291 provides and don't use builtin python constructs such as the string modulo
292 operator.
293
294 Functions returning template data (macros, `super`, `self.BLOCKNAME`) return
295 safe markup always.
296
297 String literals in templates with automatic escaping are considered unsafe
298 too.  The reason for this is that the safe string is an extension to python
299 and not every library will work properly with it.
300
301
302 .. _builtin-filters:
303
304 List of Builtin Filters
305 -----------------------
306
307 .. jinjafilters::
308
309
310 .. _builtin-tests:
311
312 List of Builtin Tests
313 ---------------------
314
315 bleh