1 | ==================================================
|
---|
2 | The Django template language: For template authors
|
---|
3 | ==================================================
|
---|
4 |
|
---|
5 | Django's template language is designed to strike a balance between power and
|
---|
6 | ease. It's designed to feel comfortable to those used to working with HTML. If
|
---|
7 | you have any exposure to other text-based template languages, such as Smarty_
|
---|
8 | or CheetahTemplate_, you should feel right at home with Django's templates.
|
---|
9 |
|
---|
10 | .. _Smarty: http://smarty.php.net/
|
---|
11 | .. _CheetahTemplate: http://www.cheetahtemplate.org/
|
---|
12 |
|
---|
13 | Templates
|
---|
14 | =========
|
---|
15 |
|
---|
16 | A template is simply a text file. It can generate any text-based format (HTML,
|
---|
17 | XML, CSV, etc.).
|
---|
18 |
|
---|
19 | A template contains **variables**, which get replaced with values when the
|
---|
20 | template is evaluated, and **tags**, which control the logic of the template.
|
---|
21 |
|
---|
22 | Below is a minimal template that illustrates a few basics. Each element will be
|
---|
23 | explained later in this document.::
|
---|
24 |
|
---|
25 | {% extends "base_generic.html" %}
|
---|
26 |
|
---|
27 | {% block title %}{{ section.title }}{% endblock %}
|
---|
28 |
|
---|
29 | {% block content %}
|
---|
30 | <h1>{{ section.title }}</h1>
|
---|
31 |
|
---|
32 | {% for story in story_list %}
|
---|
33 | <h2>
|
---|
34 | <a href="{{ story.get_absolute_url }}">
|
---|
35 | {{ story.headline|upper }}
|
---|
36 | </a>
|
---|
37 | </h2>
|
---|
38 | <p>{{ story.tease|truncatewords:"100" }}</p>
|
---|
39 | {% endfor %}
|
---|
40 | {% endblock %}
|
---|
41 |
|
---|
42 | .. admonition:: Philosophy
|
---|
43 |
|
---|
44 | Why use a text-based template instead of an XML-based one (like Zope's
|
---|
45 | TAL)? We wanted Django's template language to be usable for more than
|
---|
46 | just XML/HTML templates. At World Online, we use it for e-mails,
|
---|
47 | JavaScript and CSV. You can use the template language for any text-based
|
---|
48 | format.
|
---|
49 |
|
---|
50 | Oh, and one more thing: Making humans edit XML is sadistic!
|
---|
51 |
|
---|
52 | Variables
|
---|
53 | =========
|
---|
54 |
|
---|
55 | Variables look like this: ``{{ variable }}``. When the template engine
|
---|
56 | encounters a variable, it evaluates that variable and replaces it with the
|
---|
57 | result.
|
---|
58 |
|
---|
59 | Use a dot (``.``) to access attributes of a variable.
|
---|
60 |
|
---|
61 | .. admonition:: Behind the scenes
|
---|
62 |
|
---|
63 | Technically, when the template system encounters a dot, it tries the
|
---|
64 | following lookups, in this order:
|
---|
65 |
|
---|
66 | * Dictionary lookup
|
---|
67 | * Attribute lookup
|
---|
68 | * Method call
|
---|
69 | * List-index lookup
|
---|
70 |
|
---|
71 | In the above example, ``{{ section.title }}`` will be replaced with the
|
---|
72 | ``title`` attribute of the ``section`` object.
|
---|
73 |
|
---|
74 | If you use a variable that doesn't exist, the template system will insert
|
---|
75 | the value of the ``TEMPLATE_STRING_IF_INVALID`` setting, which is set to ``''``
|
---|
76 | (the empty string) by default.
|
---|
77 |
|
---|
78 | See `Using the built-in reference`_, below, for help on finding what variables
|
---|
79 | are available in a given template.
|
---|
80 |
|
---|
81 | Filters
|
---|
82 | =======
|
---|
83 |
|
---|
84 | You can modify variables for display by using **filters**.
|
---|
85 |
|
---|
86 | Filters look like this: ``{{ name|lower }}``. This displays the value of the
|
---|
87 | ``{{ name }}`` variable after being filtered through the ``lower`` filter,
|
---|
88 | which converts text to lowercase. Use a pipe (``|``) to apply a filter.
|
---|
89 |
|
---|
90 | Filters can be "chained." The output of one filter is applied to the next.
|
---|
91 | ``{{ text|escape|linebreaks }}`` is a common idiom for escaping text contents,
|
---|
92 | then converting line breaks to ``<p>`` tags.
|
---|
93 |
|
---|
94 | Some filters take arguments. A filter argument looks like this: ``{{
|
---|
95 | bio|truncatewords:30 }}``. This will display the first 30 words of the ``bio``
|
---|
96 | variable.
|
---|
97 |
|
---|
98 | Filter arguments that contain spaces must be quoted; for example, to join a list
|
---|
99 | with commas and spaced you'd use ``{{ list|join:", " }}``.
|
---|
100 |
|
---|
101 | The `Built-in filter reference`_ below describes all the built-in filters.
|
---|
102 |
|
---|
103 | Tags
|
---|
104 | ====
|
---|
105 |
|
---|
106 | Tags look like this: ``{% tag %}``. Tags are more complex than variables: Some
|
---|
107 | create text in the output, some control flow by performing loops or logic, and
|
---|
108 | some load external information into the template to be used by later variables.
|
---|
109 |
|
---|
110 | Some tags require beginning and ending tags (i.e.
|
---|
111 | ``{% tag %} ... tag contents ... {% endtag %}``). The `Built-in tag reference`_
|
---|
112 | below describes all the built-in tags. You can create your own tags, if you
|
---|
113 | know how to write Python code.
|
---|
114 |
|
---|
115 | Comments
|
---|
116 | ========
|
---|
117 |
|
---|
118 | To comment-out part of a line in a template, use the comment syntax: ``{# #}``.
|
---|
119 |
|
---|
120 | For example, this template would render as ``'hello'``::
|
---|
121 |
|
---|
122 | {# greeting #}hello
|
---|
123 |
|
---|
124 | A comment can contain any template code, invalid or not. For example::
|
---|
125 |
|
---|
126 | {# {% if foo %}bar{% else %} #}
|
---|
127 |
|
---|
128 | This syntax can only be used for single-line comments (no newlines are
|
---|
129 | permitted between the ``{#`` and ``#}`` delimiters). If you need to comment
|
---|
130 | out a multiline portion of the template, see the ``comment`` tag, below__.
|
---|
131 |
|
---|
132 | __ comment_
|
---|
133 |
|
---|
134 | Template inheritance
|
---|
135 | ====================
|
---|
136 |
|
---|
137 | The most powerful -- and thus the most complex -- part of Django's template
|
---|
138 | engine is template inheritance. Template inheritance allows you to build a base
|
---|
139 | "skeleton" template that contains all the common elements of your site and
|
---|
140 | defines **blocks** that child templates can override.
|
---|
141 |
|
---|
142 | It's easiest to understand template inheritance by starting with an example::
|
---|
143 |
|
---|
144 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
|
---|
145 | "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
---|
146 | <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
---|
147 | <head>
|
---|
148 | <link rel="stylesheet" href="style.css" />
|
---|
149 | <title>{% block title %}My amazing site{% endblock %}</title>
|
---|
150 | </head>
|
---|
151 |
|
---|
152 | <body>
|
---|
153 | <div id="sidebar">
|
---|
154 | {% block sidebar %}
|
---|
155 | <ul>
|
---|
156 | <li><a href="/">Home</a></li>
|
---|
157 | <li><a href="/blog/">Blog</a></li>
|
---|
158 | </ul>
|
---|
159 | {% endblock %}
|
---|
160 | </div>
|
---|
161 |
|
---|
162 | <div id="content">
|
---|
163 | {% block content %}{% endblock %}
|
---|
164 | </div>
|
---|
165 | </body>
|
---|
166 | </html>
|
---|
167 |
|
---|
168 | This template, which we'll call ``base.html``, defines a simple HTML skeleton
|
---|
169 | document that you might use for a simple two-column page. It's the job of
|
---|
170 | "child" templates to fill the empty blocks with content.
|
---|
171 |
|
---|
172 | In this example, the ``{% block %}`` tag defines three blocks that child
|
---|
173 | templates can fill in. All the ``block`` tag does is to tell the template
|
---|
174 | engine that a child template may override those portions of the template.
|
---|
175 |
|
---|
176 | A child template might look like this::
|
---|
177 |
|
---|
178 | {% extends "base.html" %}
|
---|
179 |
|
---|
180 | {% block title %}My amazing blog{% endblock %}
|
---|
181 |
|
---|
182 | {% block content %}
|
---|
183 | {% for entry in blog_entries %}
|
---|
184 | <h2>{{ entry.title }}</h2>
|
---|
185 | <p>{{ entry.body }}</p>
|
---|
186 | {% endfor %}
|
---|
187 | {% endblock %}
|
---|
188 |
|
---|
189 | The ``{% extends %}`` tag is the key here. It tells the template engine that
|
---|
190 | this template "extends" another template. When the template system evaluates
|
---|
191 | this template, first it locates the parent -- in this case, "base.html".
|
---|
192 |
|
---|
193 | At that point, the template engine will notice the three ``{% block %}`` tags
|
---|
194 | in ``base.html`` and replace those blocks with the contents of the child
|
---|
195 | template. Depending on the value of ``blog_entries``, the output might look
|
---|
196 | like::
|
---|
197 |
|
---|
198 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
|
---|
199 | "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
---|
200 | <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
---|
201 | <head>
|
---|
202 | <link rel="stylesheet" href="style.css" />
|
---|
203 | <title>My amazing blog</title>
|
---|
204 | </head>
|
---|
205 |
|
---|
206 | <body>
|
---|
207 | <div id="sidebar">
|
---|
208 | <ul>
|
---|
209 | <li><a href="/">Home</a></li>
|
---|
210 | <li><a href="/blog/">Blog</a></li>
|
---|
211 | </ul>
|
---|
212 | </div>
|
---|
213 |
|
---|
214 | <div id="content">
|
---|
215 | <h2>Entry one</h2>
|
---|
216 | <p>This is my first entry.</p>
|
---|
217 |
|
---|
218 | <h2>Entry two</h2>
|
---|
219 | <p>This is my second entry.</p>
|
---|
220 | </div>
|
---|
221 | </body>
|
---|
222 | </html>
|
---|
223 |
|
---|
224 | Note that since the child template didn't define the ``sidebar`` block, the
|
---|
225 | value from the parent template is used instead. Content within a ``{% block %}``
|
---|
226 | tag in a parent template is always used as a fallback.
|
---|
227 |
|
---|
228 | You can use as many levels of inheritance as needed. One common way of using
|
---|
229 | inheritance is the following three-level approach:
|
---|
230 |
|
---|
231 | * Create a ``base.html`` template that holds the main look-and-feel of your
|
---|
232 | site.
|
---|
233 | * Create a ``base_SECTIONNAME.html`` template for each "section" of your
|
---|
234 | site. For example, ``base_news.html``, ``base_sports.html``. These
|
---|
235 | templates all extend ``base.html`` and include section-specific
|
---|
236 | styles/design.
|
---|
237 | * Create individual templates for each type of page, such as a news
|
---|
238 | article or blog entry. These templates extend the appropriate section
|
---|
239 | template.
|
---|
240 |
|
---|
241 | This approach maximizes code reuse and makes it easy to add items to shared
|
---|
242 | content areas, such as section-wide navigation.
|
---|
243 |
|
---|
244 | Here are some tips for working with inheritance:
|
---|
245 |
|
---|
246 | * If you use ``{% extends %}`` in a template, it must be the first template
|
---|
247 | tag in that template. Template inheritance won't work, otherwise.
|
---|
248 |
|
---|
249 | * More ``{% block %}`` tags in your base templates are better. Remember,
|
---|
250 | child templates don't have to define all parent blocks, so you can fill
|
---|
251 | in reasonable defaults in a number of blocks, then only define the ones
|
---|
252 | you need later. It's better to have more hooks than fewer hooks.
|
---|
253 |
|
---|
254 | * If you find yourself duplicating content in a number of templates, it
|
---|
255 | probably means you should move that content to a ``{% block %}`` in a
|
---|
256 | parent template.
|
---|
257 |
|
---|
258 | * If you need to get the content of the block from the parent template,
|
---|
259 | the ``{{ block.super }}`` variable will do the trick. This is useful
|
---|
260 | if you want to add to the contents of a parent block instead of
|
---|
261 | completely overriding it.
|
---|
262 |
|
---|
263 | * For extra readability, you can optionally give a *name* to your
|
---|
264 | ``{% endblock %}`` tag. For example::
|
---|
265 |
|
---|
266 | {% block content %}
|
---|
267 | ...
|
---|
268 | {% endblock content %}
|
---|
269 |
|
---|
270 | In larger templates, this technique helps you see which ``{% block %}``
|
---|
271 | tags are being closed.
|
---|
272 |
|
---|
273 | Finally, note that you can't define multiple ``{% block %}`` tags with the same
|
---|
274 | name in the same template. This limitation exists because a block tag works in
|
---|
275 | "both" directions. That is, a block tag doesn't just provide a hole to fill --
|
---|
276 | it also defines the content that fills the hole in the *parent*. If there were
|
---|
277 | two similarly-named ``{% block %}`` tags in a template, that template's parent
|
---|
278 | wouldn't know which one of the blocks' content to use.
|
---|
279 |
|
---|
280 | Using the built-in reference
|
---|
281 | ============================
|
---|
282 |
|
---|
283 | Django's admin interface includes a complete reference of all template tags and
|
---|
284 | filters available for a given site. To see it, go to your admin interface and
|
---|
285 | click the "Documentation" link in the upper right of the page.
|
---|
286 |
|
---|
287 | The reference is divided into 4 sections: tags, filters, models, and views.
|
---|
288 |
|
---|
289 | The **tags** and **filters** sections describe all the built-in tags (in fact,
|
---|
290 | the tag and filter references below come directly from those pages) as well as
|
---|
291 | any custom tag or filter libraries available.
|
---|
292 |
|
---|
293 | The **views** page is the most valuable. Each URL in your site has a separate
|
---|
294 | entry here, and clicking on a URL will show you:
|
---|
295 |
|
---|
296 | * The name of the view function that generates that view.
|
---|
297 | * A short description of what the view does.
|
---|
298 | * The **context**, or a list of variables available in the view's template.
|
---|
299 | * The name of the template or templates that are used for that view.
|
---|
300 |
|
---|
301 | Each view documentation page also has a bookmarklet that you can use to jump
|
---|
302 | from any page to the documentation page for that view.
|
---|
303 |
|
---|
304 | Because Django-powered sites usually use database objects, the **models**
|
---|
305 | section of the documentation page describes each type of object in the system
|
---|
306 | along with all the fields available on that object.
|
---|
307 |
|
---|
308 | Taken together, the documentation pages should tell you every tag, filter,
|
---|
309 | variable and object available to you in a given template.
|
---|
310 |
|
---|
311 | Custom tag and filter libraries
|
---|
312 | ===============================
|
---|
313 |
|
---|
314 | Certain applications provide custom tag and filter libraries. To access them in
|
---|
315 | a template, use the ``{% load %}`` tag::
|
---|
316 |
|
---|
317 | {% load comments %}
|
---|
318 |
|
---|
319 | {% comment_form for blogs.entries entry.id with is_public yes %}
|
---|
320 |
|
---|
321 | In the above, the ``load`` tag loads the ``comments`` tag library, which then
|
---|
322 | makes the ``comment_form`` tag available for use. Consult the documentation
|
---|
323 | area in your admin to find the list of custom libraries in your installation.
|
---|
324 |
|
---|
325 | The ``{% load %}`` tag can take multiple library names, separated by spaces.
|
---|
326 | Example::
|
---|
327 |
|
---|
328 | {% load comments i18n %}
|
---|
329 |
|
---|
330 | Custom libraries and template inheritance
|
---|
331 | -----------------------------------------
|
---|
332 |
|
---|
333 | When you load a custom tag or filter library, the tags/filters are only made
|
---|
334 | available to the current template -- not any parent or child templates along
|
---|
335 | the template-inheritance path.
|
---|
336 |
|
---|
337 | For example, if a template ``foo.html`` has ``{% load comments %}``, a child
|
---|
338 | template (e.g., one that has ``{% extends "foo.html" %}``) will *not* have
|
---|
339 | access to the comments template tags and filters. The child template is
|
---|
340 | responsible for its own ``{% load comments %}``.
|
---|
341 |
|
---|
342 | This is a feature for the sake of maintainability and sanity.
|
---|
343 |
|
---|
344 | Built-in tag and filter reference
|
---|
345 | =================================
|
---|
346 |
|
---|
347 | For those without an admin site available, reference for the stock tags and
|
---|
348 | filters follows. Because Django is highly customizable, the reference in your
|
---|
349 | admin should be considered the final word on what tags and filters are
|
---|
350 | available, and what they do.
|
---|
351 |
|
---|
352 | Built-in tag reference
|
---|
353 | ----------------------
|
---|
354 |
|
---|
355 | block
|
---|
356 | ~~~~~
|
---|
357 |
|
---|
358 | Define a block that can be overridden by child templates. See
|
---|
359 | `Template inheritance`_ for more information.
|
---|
360 |
|
---|
361 | comment
|
---|
362 | ~~~~~~~
|
---|
363 |
|
---|
364 | Ignore everything between ``{% comment %}`` and ``{% endcomment %}``
|
---|
365 |
|
---|
366 | cycle
|
---|
367 | ~~~~~
|
---|
368 |
|
---|
369 | **Changed in Django development version**
|
---|
370 | Cycle among the given strings or variables each time this tag is encountered.
|
---|
371 |
|
---|
372 | Within a loop, cycles among the given strings/variables each time through the
|
---|
373 | loop::
|
---|
374 |
|
---|
375 | {% for o in some_list %}
|
---|
376 | <tr class="{% cycle 'row1' 'row2' rowvar %}">
|
---|
377 | ...
|
---|
378 | </tr>
|
---|
379 | {% endfor %}
|
---|
380 |
|
---|
381 | Outside of a loop, give the values a unique name the first time you call it,
|
---|
382 | then use that name each successive time through::
|
---|
383 |
|
---|
384 | <tr class="{% cycle 'row1' 'row2' rowvar as rowcolors %}">...</tr>
|
---|
385 | <tr class="{% cycle rowcolors %}">...</tr>
|
---|
386 | <tr class="{% cycle rowcolors %}">...</tr>
|
---|
387 |
|
---|
388 | You can use any number of values, separated by spaces. Values enclosed in
|
---|
389 | single (') or double quotes (") are treated as string literals, while values
|
---|
390 | without quotes are assumed to refer to context variables.
|
---|
391 |
|
---|
392 | You can also separate values with commas::
|
---|
393 |
|
---|
394 | {% cycle row1,row2,row3 %}
|
---|
395 |
|
---|
396 | In this syntax, each value will be interpreted as literal text. The
|
---|
397 | comma-based syntax exists for backwards-compatibility, and should not be
|
---|
398 | used for new projects.
|
---|
399 |
|
---|
400 | debug
|
---|
401 | ~~~~~
|
---|
402 |
|
---|
403 | Output a whole load of debugging information, including the current context and
|
---|
404 | imported modules.
|
---|
405 |
|
---|
406 | extends
|
---|
407 | ~~~~~~~
|
---|
408 |
|
---|
409 | Signal that this template extends a parent template.
|
---|
410 |
|
---|
411 | This tag can be used in two ways:
|
---|
412 |
|
---|
413 | * ``{% extends "base.html" %}`` (with quotes) uses the literal value
|
---|
414 | ``"base.html"`` as the name of the parent template to extend.
|
---|
415 |
|
---|
416 | * ``{% extends variable %}`` uses the value of ``variable``. If the variable
|
---|
417 | evaluates to a string, Django will use that string as the name of the
|
---|
418 | parent template. If the variable evaluates to a ``Template`` object,
|
---|
419 | Django will use that object as the parent template.
|
---|
420 |
|
---|
421 | See `Template inheritance`_ for more information.
|
---|
422 |
|
---|
423 | filter
|
---|
424 | ~~~~~~
|
---|
425 |
|
---|
426 | Filter the contents of the variable through variable filters.
|
---|
427 |
|
---|
428 | Filters can also be piped through each other, and they can have arguments --
|
---|
429 | just like in variable syntax.
|
---|
430 |
|
---|
431 | Sample usage::
|
---|
432 |
|
---|
433 | {% filter escape|lower %}
|
---|
434 | This text will be HTML-escaped, and will appear in all lowercase.
|
---|
435 | {% endfilter %}
|
---|
436 |
|
---|
437 | firstof
|
---|
438 | ~~~~~~~
|
---|
439 |
|
---|
440 | Outputs the first variable passed that is not False. Outputs nothing if all the
|
---|
441 | passed variables are False.
|
---|
442 |
|
---|
443 | Sample usage::
|
---|
444 |
|
---|
445 | {% firstof var1 var2 var3 %}
|
---|
446 |
|
---|
447 | This is equivalent to::
|
---|
448 |
|
---|
449 | {% if var1 %}
|
---|
450 | {{ var1 }}
|
---|
451 | {% else %}{% if var2 %}
|
---|
452 | {{ var2 }}
|
---|
453 | {% else %}{% if var3 %}
|
---|
454 | {{ var3 }}
|
---|
455 | {% endif %}{% endif %}{% endif %}
|
---|
456 |
|
---|
457 | for
|
---|
458 | ~~~
|
---|
459 |
|
---|
460 | Loop over each item in an array. For example, to display a list of athletes
|
---|
461 | provided in ``athlete_list``::
|
---|
462 |
|
---|
463 | <ul>
|
---|
464 | {% for athlete in athlete_list %}
|
---|
465 | <li>{{ athlete.name }}</li>
|
---|
466 | {% endfor %}
|
---|
467 | </ul>
|
---|
468 |
|
---|
469 | You can loop over a list in reverse by using ``{% for obj in list reversed %}``.
|
---|
470 |
|
---|
471 | **New in Django development version**
|
---|
472 | If you need to loop over a list of lists, you can unpack the values
|
---|
473 | in eachs sub-list into a set of known names. For example, if your context contains
|
---|
474 | a list of (x,y) coordinates called ``points``, you could use the following
|
---|
475 | to output the list of points::
|
---|
476 |
|
---|
477 | {% for x, y in points %}
|
---|
478 | There is a point at {{ x }},{{ y }}
|
---|
479 | {% endfor %}
|
---|
480 |
|
---|
481 | This can also be useful if you need to access the items in a dictionary.
|
---|
482 | For example, if your context contained a dictionary ``data``, the following
|
---|
483 | would display the keys and values of the dictionary::
|
---|
484 |
|
---|
485 | {% for key, value in data.items %}
|
---|
486 | {{ key }}: {{ value }}
|
---|
487 | {% endfor %}
|
---|
488 |
|
---|
489 | The for loop sets a number of variables available within the loop:
|
---|
490 |
|
---|
491 | ========================== ================================================
|
---|
492 | Variable Description
|
---|
493 | ========================== ================================================
|
---|
494 | ``forloop.counter`` The current iteration of the loop (1-indexed)
|
---|
495 | ``forloop.counter0`` The current iteration of the loop (0-indexed)
|
---|
496 | ``forloop.revcounter`` The number of iterations from the end of the
|
---|
497 | loop (1-indexed)
|
---|
498 | ``forloop.revcounter0`` The number of iterations from the end of the
|
---|
499 | loop (0-indexed)
|
---|
500 | ``forloop.first`` True if this is the first time through the loop
|
---|
501 | ``forloop.last`` True if this is the last time through the loop
|
---|
502 | ``forloop.parentloop`` For nested loops, this is the loop "above" the
|
---|
503 | current one
|
---|
504 | ========================== ================================================
|
---|
505 |
|
---|
506 | if
|
---|
507 | ~~
|
---|
508 |
|
---|
509 | The ``{% if %}`` tag evaluates a variable, and if that variable is "true" (i.e.
|
---|
510 | exists, is not empty, and is not a false boolean value) the contents of the
|
---|
511 | block are output::
|
---|
512 |
|
---|
513 | {% if athlete_list %}
|
---|
514 | Number of athletes: {{ athlete_list|length }}
|
---|
515 | {% else %}
|
---|
516 | No athletes.
|
---|
517 | {% endif %}
|
---|
518 |
|
---|
519 | In the above, if ``athlete_list`` is not empty, the number of athletes will be
|
---|
520 | displayed by the ``{{ athlete_list|length }}`` variable.
|
---|
521 |
|
---|
522 | As you can see, the ``if`` tag can take an optional ``{% else %}`` clause that
|
---|
523 | will be displayed if the test fails.
|
---|
524 |
|
---|
525 | ``if`` tags may use ``and``, ``or`` or ``not`` to test a number of variables or
|
---|
526 | to negate a given variable::
|
---|
527 |
|
---|
528 | {% if athlete_list and coach_list %}
|
---|
529 | Both athletes and coaches are available.
|
---|
530 | {% endif %}
|
---|
531 |
|
---|
532 | {% if not athlete_list %}
|
---|
533 | There are no athletes.
|
---|
534 | {% endif %}
|
---|
535 |
|
---|
536 | {% if athlete_list or coach_list %}
|
---|
537 | There are some athletes or some coaches.
|
---|
538 | {% endif %}
|
---|
539 |
|
---|
540 | {% if not athlete_list or coach_list %}
|
---|
541 | There are no athletes or there are some coaches (OK, so
|
---|
542 | writing English translations of boolean logic sounds
|
---|
543 | stupid; it's not our fault).
|
---|
544 | {% endif %}
|
---|
545 |
|
---|
546 | {% if athlete_list and not coach_list %}
|
---|
547 | There are some athletes and absolutely no coaches.
|
---|
548 | {% endif %}
|
---|
549 |
|
---|
550 | ``if`` tags don't allow ``and`` and ``or`` clauses within the same tag, because
|
---|
551 | the order of logic would be ambiguous. For example, this is invalid::
|
---|
552 |
|
---|
553 | {% if athlete_list and coach_list or cheerleader_list %}
|
---|
554 |
|
---|
555 | If you need to combine ``and`` and ``or`` to do advanced logic, just use nested
|
---|
556 | ``if`` tags. For example::
|
---|
557 |
|
---|
558 | {% if athlete_list %}
|
---|
559 | {% if coach_list or cheerleader_list %}
|
---|
560 | We have athletes, and either coaches or cheerleaders!
|
---|
561 | {% endif %}
|
---|
562 | {% endif %}
|
---|
563 |
|
---|
564 | Multiple uses of the same logical operator are fine, as long as you use the
|
---|
565 | same operator. For example, this is valid::
|
---|
566 |
|
---|
567 | {% if athlete_list or coach_list or parent_list or teacher_list %}
|
---|
568 |
|
---|
569 | ifchanged
|
---|
570 | ~~~~~~~~~
|
---|
571 |
|
---|
572 | Check if a value has changed from the last iteration of a loop.
|
---|
573 |
|
---|
574 | The 'ifchanged' block tag is used within a loop. It has two possible uses.
|
---|
575 |
|
---|
576 | 1. Checks its own rendered contents against its previous state and only
|
---|
577 | displays the content if it has changed. For example, this displays a list of
|
---|
578 | days, only displaying the month if it changes::
|
---|
579 |
|
---|
580 | <h1>Archive for {{ year }}</h1>
|
---|
581 |
|
---|
582 | {% for date in days %}
|
---|
583 | {% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %}
|
---|
584 | <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a>
|
---|
585 | {% endfor %}
|
---|
586 |
|
---|
587 | 2. If given a variable, check whether that variable has changed. For
|
---|
588 | example, the following shows the date every time it changes, but
|
---|
589 | only shows the hour if both the hour and the date has changed::
|
---|
590 |
|
---|
591 | {% for date in days %}
|
---|
592 | {% ifchanged date.date %} {{ date.date }} {% endifchanged %}
|
---|
593 | {% ifchanged date.hour date.date %}
|
---|
594 | {{ date.hour }}
|
---|
595 | {% endifchanged %}
|
---|
596 | {% endfor %}
|
---|
597 |
|
---|
598 | ifequal
|
---|
599 | ~~~~~~~
|
---|
600 |
|
---|
601 | Output the contents of the block if the two arguments equal each other.
|
---|
602 |
|
---|
603 | Example::
|
---|
604 |
|
---|
605 | {% ifequal user.id comment.user_id %}
|
---|
606 | ...
|
---|
607 | {% endifequal %}
|
---|
608 |
|
---|
609 | As in the ``{% if %}`` tag, an ``{% else %}`` clause is optional.
|
---|
610 |
|
---|
611 | The arguments can be hard-coded strings, so the following is valid::
|
---|
612 |
|
---|
613 | {% ifequal user.username "adrian" %}
|
---|
614 | ...
|
---|
615 | {% endifequal %}
|
---|
616 |
|
---|
617 | It is only possible to compare an argument to template variables or strings.
|
---|
618 | You cannot check for equality with Python objects such as ``True`` or
|
---|
619 | ``False``. If you need to test if something is true or false, use the ``if``
|
---|
620 | tag instead.
|
---|
621 |
|
---|
622 | ifnotequal
|
---|
623 | ~~~~~~~~~~
|
---|
624 |
|
---|
625 | Just like ``ifequal``, except it tests that the two arguments are not equal.
|
---|
626 |
|
---|
627 | include
|
---|
628 | ~~~~~~~
|
---|
629 |
|
---|
630 | Loads a template and renders it with the current context. This is a way of
|
---|
631 | "including" other templates within a template.
|
---|
632 |
|
---|
633 | The template name can either be a variable or a hard-coded (quoted) string,
|
---|
634 | in either single or double quotes.
|
---|
635 |
|
---|
636 | This example includes the contents of the template ``"foo/bar.html"``::
|
---|
637 |
|
---|
638 | {% include "foo/bar.html" %}
|
---|
639 |
|
---|
640 | This example includes the contents of the template whose name is contained in
|
---|
641 | the variable ``template_name``::
|
---|
642 |
|
---|
643 | {% include template_name %}
|
---|
644 |
|
---|
645 | An included template is rendered with the context of the template that's
|
---|
646 | including it. This example produces the output ``"Hello, John"``:
|
---|
647 |
|
---|
648 | * Context: variable ``person`` is set to ``"john"``.
|
---|
649 | * Template::
|
---|
650 |
|
---|
651 | {% include "name_snippet.html" %}
|
---|
652 |
|
---|
653 | * The ``name_snippet.html`` template::
|
---|
654 |
|
---|
655 | Hello, {{ person }}
|
---|
656 |
|
---|
657 | See also: ``{% ssi %}``.
|
---|
658 |
|
---|
659 | load
|
---|
660 | ~~~~
|
---|
661 |
|
---|
662 | Load a custom template tag set.
|
---|
663 |
|
---|
664 | See `Custom tag and filter libraries`_ for more information.
|
---|
665 |
|
---|
666 | now
|
---|
667 | ~~~
|
---|
668 |
|
---|
669 | Display the date, formatted according to the given string.
|
---|
670 |
|
---|
671 | Uses the same format as PHP's ``date()`` function (http://php.net/date)
|
---|
672 | with some custom extensions.
|
---|
673 |
|
---|
674 | Available format strings:
|
---|
675 |
|
---|
676 | ================ ======================================== =====================
|
---|
677 | Format character Description Example output
|
---|
678 | ================ ======================================== =====================
|
---|
679 | a ``'a.m.'`` or ``'p.m.'`` (Note that ``'a.m.'``
|
---|
680 | this is slightly different than PHP's
|
---|
681 | output, because this includes periods
|
---|
682 | to match Associated Press style.)
|
---|
683 | A ``'AM'`` or ``'PM'``. ``'AM'``
|
---|
684 | b Month, textual, 3 letters, lowercase. ``'jan'``
|
---|
685 | B Not implemented.
|
---|
686 | d Day of the month, 2 digits with ``'01'`` to ``'31'``
|
---|
687 | leading zeros.
|
---|
688 | D Day of the week, textual, 3 letters. ``'Fri'``
|
---|
689 | f Time, in 12-hour hours and minutes, ``'1'``, ``'1:30'``
|
---|
690 | with minutes left off if they're zero.
|
---|
691 | Proprietary extension.
|
---|
692 | F Month, textual, long. ``'January'``
|
---|
693 | g Hour, 12-hour format without leading ``'1'`` to ``'12'``
|
---|
694 | zeros.
|
---|
695 | G Hour, 24-hour format without leading ``'0'`` to ``'23'``
|
---|
696 | zeros.
|
---|
697 | h Hour, 12-hour format. ``'01'`` to ``'12'``
|
---|
698 | H Hour, 24-hour format. ``'00'`` to ``'23'``
|
---|
699 | i Minutes. ``'00'`` to ``'59'``
|
---|
700 | I Not implemented.
|
---|
701 | j Day of the month without leading ``'1'`` to ``'31'``
|
---|
702 | zeros.
|
---|
703 | l Day of the week, textual, long. ``'Friday'``
|
---|
704 | L Boolean for whether it's a leap year. ``True`` or ``False``
|
---|
705 | m Month, 2 digits with leading zeros. ``'01'`` to ``'12'``
|
---|
706 | M Month, textual, 3 letters. ``'Jan'``
|
---|
707 | n Month without leading zeros. ``'1'`` to ``'12'``
|
---|
708 | N Month abbreviation in Associated Press ``'Jan.'``, ``'Feb.'``, ``'March'``, ``'May'``
|
---|
709 | style. Proprietary extension.
|
---|
710 | O Difference to Greenwich time in hours. ``'+0200'``
|
---|
711 | P Time, in 12-hour hours, minutes and ``'1 a.m.'``, ``'1:30 p.m.'``, ``'midnight'``, ``'noon'``, ``'12:30 p.m.'``
|
---|
712 | 'a.m.'/'p.m.', with minutes left off
|
---|
713 | if they're zero and the special-case
|
---|
714 | strings 'midnight' and 'noon' if
|
---|
715 | appropriate. Proprietary extension.
|
---|
716 | r RFC 822 formatted date. ``'Thu, 21 Dec 2000 16:01:07 +0200'``
|
---|
717 | s Seconds, 2 digits with leading zeros. ``'00'`` to ``'59'``
|
---|
718 | S English ordinal suffix for day of the ``'st'``, ``'nd'``, ``'rd'`` or ``'th'``
|
---|
719 | month, 2 characters.
|
---|
720 | t Number of days in the given month. ``28`` to ``31``
|
---|
721 | T Time zone of this machine. ``'EST'``, ``'MDT'``
|
---|
722 | U Not implemented.
|
---|
723 | w Day of the week, digits without ``'0'`` (Sunday) to ``'6'`` (Saturday)
|
---|
724 | leading zeros.
|
---|
725 | W ISO-8601 week number of year, with ``1``, ``23``
|
---|
726 | weeks starting on Monday.
|
---|
727 | y Year, 2 digits. ``'99'``
|
---|
728 | Y Year, 4 digits. ``'1999'``
|
---|
729 | z Day of the year. ``0`` to ``365``
|
---|
730 | Z Time zone offset in seconds. The ``-43200`` to ``43200``
|
---|
731 | offset for timezones west of UTC is
|
---|
732 | always negative, and for those east of
|
---|
733 | UTC is always positive.
|
---|
734 | ================ ======================================== =====================
|
---|
735 |
|
---|
736 | Example::
|
---|
737 |
|
---|
738 | It is {% now "jS F Y H:i" %}
|
---|
739 |
|
---|
740 | Note that you can backslash-escape a format string if you want to use the
|
---|
741 | "raw" value. In this example, "f" is backslash-escaped, because otherwise
|
---|
742 | "f" is a format string that displays the time. The "o" doesn't need to be
|
---|
743 | escaped, because it's not a format character::
|
---|
744 |
|
---|
745 | It is the {% now "jS o\f F" %}
|
---|
746 |
|
---|
747 | This would display as "It is the 4th of September".
|
---|
748 |
|
---|
749 | regroup
|
---|
750 | ~~~~~~~
|
---|
751 |
|
---|
752 | Regroup a list of alike objects by a common attribute.
|
---|
753 |
|
---|
754 | This complex tag is best illustrated by use of an example: say that ``people``
|
---|
755 | is a list of people represented by dictionaries with ``first_name``,
|
---|
756 | ``last_name``, and ``gender`` keys::
|
---|
757 |
|
---|
758 | people = [
|
---|
759 | {'first_name': 'George', 'last_name': 'Bush', 'gender': 'Male'},
|
---|
760 | {'first_name': 'Bill', 'last_name': 'Clinton', 'gender': 'Male'},
|
---|
761 | {'first_name': 'Margaret', 'last_name': 'Thatcher', 'gender': 'Female'},
|
---|
762 | {'first_name': 'Condoleezza', 'last_name': 'Rice', 'gender': 'Female'},
|
---|
763 | {'first_name': 'Pat', 'last_name': 'Smith', 'gender': 'Unknown'},
|
---|
764 | ]
|
---|
765 |
|
---|
766 | ...and you'd like to display a hierarchical list that is ordered by gender,
|
---|
767 | like this:
|
---|
768 |
|
---|
769 | * Male:
|
---|
770 | * George Bush
|
---|
771 | * Bill Clinton
|
---|
772 | * Female:
|
---|
773 | * Margaret Thatcher
|
---|
774 | * Condoleezza Rice
|
---|
775 | * Unknown:
|
---|
776 | * Pat Smith
|
---|
777 |
|
---|
778 | You can use the ``{% regroup %}`` tag to group the list of people by gender.
|
---|
779 | The following snippet of template code would accomplish this::
|
---|
780 |
|
---|
781 | {% regroup people by gender as gender_list %}
|
---|
782 |
|
---|
783 | <ul>
|
---|
784 | {% for gender in gender_list %}
|
---|
785 | <li>{{ gender.grouper }}
|
---|
786 | <ul>
|
---|
787 | {% for item in gender.list %}
|
---|
788 | <li>{{ item.first_name }} {{ item.last_name }}</li>
|
---|
789 | {% endfor %}
|
---|
790 | </ul>
|
---|
791 | </li>
|
---|
792 | {% endfor %}
|
---|
793 | </ul>
|
---|
794 |
|
---|
795 | Let's walk through this example. ``{% regroup %}`` takes three arguments: the
|
---|
796 | list you want to regroup, the attribute to group by, and the name of the
|
---|
797 | resulting list. Here, we're regrouping the ``people`` list by the ``gender``
|
---|
798 | attribute and calling the result ``gender_list``.
|
---|
799 |
|
---|
800 | ``{% regroup %}`` produces a list (in this case, ``gender_list``) of
|
---|
801 | **group objects**. Each group object has two attributes:
|
---|
802 |
|
---|
803 | * ``grouper`` -- the item that was grouped by (e.g., the string "Male" or
|
---|
804 | "Female").
|
---|
805 | * ``list`` -- a list of all items in this group (e.g., a list of all people
|
---|
806 | with gender='Male').
|
---|
807 |
|
---|
808 | Note that ``{% regroup %}`` does not order its input! Our example relies on
|
---|
809 | the fact that the ``people`` list was ordered by ``gender`` in the first place.
|
---|
810 | If the ``people`` list did *not* order its members by ``gender``, the regrouping
|
---|
811 | would naively display more than one group for a single gender. For example,
|
---|
812 | say the ``people`` list was set to this (note that the males are not grouped
|
---|
813 | together)::
|
---|
814 |
|
---|
815 | people = [
|
---|
816 | {'first_name': 'Bill', 'last_name': 'Clinton', 'gender': 'Male'},
|
---|
817 | {'first_name': 'Pat', 'last_name': 'Smith', 'gender': 'Unknown'},
|
---|
818 | {'first_name': 'Margaret', 'last_name': 'Thatcher', 'gender': 'Female'},
|
---|
819 | {'first_name': 'George', 'last_name': 'Bush', 'gender': 'Male'},
|
---|
820 | {'first_name': 'Condoleezza', 'last_name': 'Rice', 'gender': 'Female'},
|
---|
821 | ]
|
---|
822 |
|
---|
823 | With this input for ``people``, the example ``{% regroup %}`` template code
|
---|
824 | above would result in the following output:
|
---|
825 |
|
---|
826 | * Male:
|
---|
827 | * Bill Clinton
|
---|
828 | * Unknown:
|
---|
829 | * Pat Smith
|
---|
830 | * Female:
|
---|
831 | * Margaret Thatcher
|
---|
832 | * Male:
|
---|
833 | * George Bush
|
---|
834 | * Female:
|
---|
835 | * Condoleezza Rice
|
---|
836 |
|
---|
837 | The easiest solution to this gotcha is to make sure in your view code that the
|
---|
838 | data is ordered according to how you want to display it.
|
---|
839 |
|
---|
840 | Another solution is to sort the data in the template using the ``dictsort``
|
---|
841 | filter, if your data is in a list of dictionaries::
|
---|
842 |
|
---|
843 | {% regroup people|dictsort:"gender" by gender as gender_list %}
|
---|
844 |
|
---|
845 | spaceless
|
---|
846 | ~~~~~~~~~
|
---|
847 |
|
---|
848 | Removes whitespace between HTML tags. This includes tab
|
---|
849 | characters and newlines.
|
---|
850 |
|
---|
851 | Example usage::
|
---|
852 |
|
---|
853 | {% spaceless %}
|
---|
854 | <p>
|
---|
855 | <a href="foo/">Foo</a>
|
---|
856 | </p>
|
---|
857 | {% endspaceless %}
|
---|
858 |
|
---|
859 | This example would return this HTML::
|
---|
860 |
|
---|
861 | <p><a href="foo/">Foo</a></p>
|
---|
862 |
|
---|
863 | Only space between *tags* is removed -- not space between tags and text. In
|
---|
864 | this example, the space around ``Hello`` won't be stripped::
|
---|
865 |
|
---|
866 | {% spaceless %}
|
---|
867 | <strong>
|
---|
868 | Hello
|
---|
869 | </strong>
|
---|
870 | {% endspaceless %}
|
---|
871 |
|
---|
872 | ssi
|
---|
873 | ~~~
|
---|
874 |
|
---|
875 | Output the contents of a given file into the page.
|
---|
876 |
|
---|
877 | Like a simple "include" tag, ``{% ssi %}`` includes the contents of another
|
---|
878 | file -- which must be specified using an absolute path -- in the current
|
---|
879 | page::
|
---|
880 |
|
---|
881 | {% ssi /home/html/ljworld.com/includes/right_generic.html %}
|
---|
882 |
|
---|
883 | If the optional "parsed" parameter is given, the contents of the included
|
---|
884 | file are evaluated as template code, within the current context::
|
---|
885 |
|
---|
886 | {% ssi /home/html/ljworld.com/includes/right_generic.html parsed %}
|
---|
887 |
|
---|
888 | Note that if you use ``{% ssi %}``, you'll need to define
|
---|
889 | `ALLOWED_INCLUDE_ROOTS`_ in your Django settings, as a security measure.
|
---|
890 |
|
---|
891 | See also: ``{% include %}``.
|
---|
892 |
|
---|
893 | .. _ALLOWED_INCLUDE_ROOTS: ../settings/#allowed-include-roots
|
---|
894 |
|
---|
895 | templatetag
|
---|
896 | ~~~~~~~~~~~
|
---|
897 |
|
---|
898 | Output one of the syntax characters used to compose template tags.
|
---|
899 |
|
---|
900 | Since the template system has no concept of "escaping", to display one of the
|
---|
901 | bits used in template tags, you must use the ``{% templatetag %}`` tag.
|
---|
902 |
|
---|
903 | The argument tells which template bit to output:
|
---|
904 |
|
---|
905 | ================== =======
|
---|
906 | Argument Outputs
|
---|
907 | ================== =======
|
---|
908 | ``openblock`` ``{%``
|
---|
909 | ``closeblock`` ``%}``
|
---|
910 | ``openvariable`` ``{{``
|
---|
911 | ``closevariable`` ``}}``
|
---|
912 | ``openbrace`` ``{``
|
---|
913 | ``closebrace`` ``}``
|
---|
914 | ``opencomment`` ``{#``
|
---|
915 | ``closecomment`` ``#}``
|
---|
916 | ================== =======
|
---|
917 |
|
---|
918 | url
|
---|
919 | ~~~
|
---|
920 |
|
---|
921 | **Note that the syntax for this tag may change in the future, as we make it more robust.**
|
---|
922 |
|
---|
923 | Returns an absolute URL (i.e., a URL without the domain name) matching a given
|
---|
924 | view function and optional parameters. This is a way to output links without
|
---|
925 | violating the DRY principle by having to hard-code URLs in your templates::
|
---|
926 |
|
---|
927 | {% url path.to.some_view arg1,arg2,name1=value1 %}
|
---|
928 |
|
---|
929 | The first argument is a path to a view function in the format
|
---|
930 | ``package.package.module.function``. Additional arguments are optional and
|
---|
931 | should be comma-separated values that will be used as positional and keyword
|
---|
932 | arguments in the URL. All arguments required by the URLconf should be present.
|
---|
933 |
|
---|
934 | For example, suppose you have a view, ``app_views.client``, whose URLconf
|
---|
935 | takes a client ID (here, ``client()`` is a method inside the views file
|
---|
936 | ``app_views.py``). The URLconf line might look like this::
|
---|
937 |
|
---|
938 | ('^client/(\d+)/$', 'app_views.client')
|
---|
939 |
|
---|
940 | If this app's URLconf is included into the project's URLconf under a path
|
---|
941 | such as this::
|
---|
942 |
|
---|
943 | ('^clients/', include('project_name.app_name.urls'))
|
---|
944 |
|
---|
945 | ...then, in a template, you can create a link to this view like this::
|
---|
946 |
|
---|
947 | {% url app_views.client client.id %}
|
---|
948 |
|
---|
949 | The template tag will output the string ``/clients/client/123/``.
|
---|
950 |
|
---|
951 | **New in development version:** If you're using `named URL patterns`_,
|
---|
952 | you can refer to the name of the pattern in the ``url`` tag instead of
|
---|
953 | using the path to the view.
|
---|
954 |
|
---|
955 | .. _named URL patterns: ../url_dispatch/#naming-url-patterns
|
---|
956 |
|
---|
957 | widthratio
|
---|
958 | ~~~~~~~~~~
|
---|
959 |
|
---|
960 | For creating bar charts and such, this tag calculates the ratio of a given value
|
---|
961 | to a maximum value, and then applies that ratio to a constant.
|
---|
962 |
|
---|
963 | For example::
|
---|
964 |
|
---|
965 | <img src="bar.gif" height="10" width="{% widthratio this_value max_value 100 %}" />
|
---|
966 |
|
---|
967 | Above, if ``this_value`` is 175 and ``max_value`` is 200, the the image in the
|
---|
968 | above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5
|
---|
969 | which is rounded up to 88).
|
---|
970 |
|
---|
971 | with
|
---|
972 | ~~~~
|
---|
973 |
|
---|
974 | **New in Django development version**
|
---|
975 |
|
---|
976 | Caches a complex variable under a simpler name. This is useful when accessing
|
---|
977 | an "expensive" method (e.g., one that hits the database) multiple times.
|
---|
978 |
|
---|
979 | For example::
|
---|
980 |
|
---|
981 | {% with business.employees.count as total %}
|
---|
982 | {{ total }} employee{{ total|pluralize }}
|
---|
983 | {% endwith %}
|
---|
984 |
|
---|
985 | The populated variable (in the example above, ``total``) is only available
|
---|
986 | between the ``{% with %}`` and ``{% endwith %}`` tags.
|
---|
987 |
|
---|
988 | Built-in filter reference
|
---|
989 | -------------------------
|
---|
990 |
|
---|
991 | add
|
---|
992 | ~~~
|
---|
993 |
|
---|
994 | Adds the arg to the value.
|
---|
995 |
|
---|
996 | addslashes
|
---|
997 | ~~~~~~~~~~
|
---|
998 |
|
---|
999 | Adds slashes. Useful for passing strings to JavaScript, for example.
|
---|
1000 |
|
---|
1001 |
|
---|
1002 | capfirst
|
---|
1003 | ~~~~~~~~
|
---|
1004 |
|
---|
1005 | Capitalizes the first character of the value.
|
---|
1006 |
|
---|
1007 | center
|
---|
1008 | ~~~~~~
|
---|
1009 |
|
---|
1010 | Centers the value in a field of a given width.
|
---|
1011 |
|
---|
1012 | cut
|
---|
1013 | ~~~
|
---|
1014 |
|
---|
1015 | Removes all values of arg from the given string.
|
---|
1016 |
|
---|
1017 | date
|
---|
1018 | ~~~~
|
---|
1019 |
|
---|
1020 | Formats a date according to the given format (same as the `now`_ tag).
|
---|
1021 |
|
---|
1022 | default
|
---|
1023 | ~~~~~~~
|
---|
1024 |
|
---|
1025 | If value is unavailable, use given default.
|
---|
1026 |
|
---|
1027 | default_if_none
|
---|
1028 | ~~~~~~~~~~~~~~~
|
---|
1029 |
|
---|
1030 | If value is ``None``, use given default.
|
---|
1031 |
|
---|
1032 | dictsort
|
---|
1033 | ~~~~~~~~
|
---|
1034 |
|
---|
1035 | Takes a list of dictionaries, returns that list sorted by the key given in
|
---|
1036 | the argument.
|
---|
1037 |
|
---|
1038 | dictsortreversed
|
---|
1039 | ~~~~~~~~~~~~~~~~
|
---|
1040 |
|
---|
1041 | Takes a list of dictionaries, returns that list sorted in reverse order by the
|
---|
1042 | key given in the argument.
|
---|
1043 |
|
---|
1044 | divisibleby
|
---|
1045 | ~~~~~~~~~~~
|
---|
1046 |
|
---|
1047 | Returns true if the value is divisible by the argument.
|
---|
1048 |
|
---|
1049 | escape
|
---|
1050 | ~~~~~~
|
---|
1051 |
|
---|
1052 | Escapes a string's HTML. Specifically, it makes these replacements:
|
---|
1053 |
|
---|
1054 | * ``"&"`` to ``"&"``
|
---|
1055 | * ``<`` to ``"<"``
|
---|
1056 | * ``>`` to ``">"``
|
---|
1057 | * ``'"'`` (double quote) to ``'"'``
|
---|
1058 | * ``"'"`` (single quote) to ``'''``
|
---|
1059 |
|
---|
1060 | filesizeformat
|
---|
1061 | ~~~~~~~~~~~~~~
|
---|
1062 |
|
---|
1063 | Format the value like a 'human-readable' file size (i.e. ``'13 KB'``,
|
---|
1064 | ``'4.1 MB'``, ``'102 bytes'``, etc).
|
---|
1065 |
|
---|
1066 | first
|
---|
1067 | ~~~~~
|
---|
1068 |
|
---|
1069 | Returns the first item in a list.
|
---|
1070 |
|
---|
1071 | fix_ampersands
|
---|
1072 | ~~~~~~~~~~~~~~
|
---|
1073 |
|
---|
1074 | Replaces ampersands with ``&`` entities.
|
---|
1075 |
|
---|
1076 | floatformat
|
---|
1077 | ~~~~~~~~~~~
|
---|
1078 |
|
---|
1079 | When used without an argument, rounds a floating-point number to one decimal
|
---|
1080 | place -- but only if there's a decimal part to be displayed. For example:
|
---|
1081 |
|
---|
1082 | * ``36.123`` gets converted to ``36.1``
|
---|
1083 | * ``36.15`` gets converted to ``36.2``
|
---|
1084 | * ``36`` gets converted to ``36``
|
---|
1085 |
|
---|
1086 | If used with a numeric integer argument, ``floatformat`` rounds a number to that
|
---|
1087 | many decimal places. For example:
|
---|
1088 |
|
---|
1089 | * ``36.1234`` with floatformat:3 gets converted to ``36.123``
|
---|
1090 | * ``36`` with floatformat:4 gets converted to ``36.0000``
|
---|
1091 |
|
---|
1092 | If the argument passed to ``floatformat`` is negative, it will round a number to
|
---|
1093 | that many decimal places -- but only if there's a decimal part to be displayed.
|
---|
1094 | For example:
|
---|
1095 |
|
---|
1096 | * ``36.1234`` with floatformat:-3 gets converted to ``36.123``
|
---|
1097 | * ``36`` with floatformat:-4 gets converted to ``36``
|
---|
1098 |
|
---|
1099 | Using ``floatformat`` with no argument is equivalent to using ``floatformat`` with
|
---|
1100 | an argument of ``-1``.
|
---|
1101 |
|
---|
1102 | get_digit
|
---|
1103 | ~~~~~~~~~
|
---|
1104 |
|
---|
1105 | Given a whole number, returns the requested digit of it, where 1 is the
|
---|
1106 | right-most digit, 2 is the second-right-most digit, etc. Returns the original
|
---|
1107 | value for invalid input (if input or argument is not an integer, or if argument
|
---|
1108 | is less than 1). Otherwise, output is always an integer.
|
---|
1109 |
|
---|
1110 | iriencode
|
---|
1111 | ~~~~~~~~~
|
---|
1112 |
|
---|
1113 | Converts an IRI (Internationalized Resource Identifier) to a string that is
|
---|
1114 | suitable for including in a URL. This is necessary if you're trying to use
|
---|
1115 | strings containing non-ASCII characters in a URL.
|
---|
1116 |
|
---|
1117 | It's safe to use this filter on a string that has already gone through the
|
---|
1118 | ``urlencode`` filter.
|
---|
1119 |
|
---|
1120 | join
|
---|
1121 | ~~~~
|
---|
1122 |
|
---|
1123 | Joins a list with a string, like Python's ``str.join(list)``.
|
---|
1124 |
|
---|
1125 | length
|
---|
1126 | ~~~~~~
|
---|
1127 |
|
---|
1128 | Returns the length of the value. Useful for lists.
|
---|
1129 |
|
---|
1130 | length_is
|
---|
1131 | ~~~~~~~~~
|
---|
1132 |
|
---|
1133 | Returns a boolean of whether the value's length is the argument.
|
---|
1134 |
|
---|
1135 | linebreaks
|
---|
1136 | ~~~~~~~~~~
|
---|
1137 |
|
---|
1138 | Converts newlines into ``<p>`` and ``<br />`` tags.
|
---|
1139 |
|
---|
1140 | linebreaksbr
|
---|
1141 | ~~~~~~~~~~~~
|
---|
1142 |
|
---|
1143 | Converts newlines into ``<br />`` tags.
|
---|
1144 |
|
---|
1145 | linenumbers
|
---|
1146 | ~~~~~~~~~~~
|
---|
1147 |
|
---|
1148 | Displays text with line numbers.
|
---|
1149 |
|
---|
1150 | ljust
|
---|
1151 | ~~~~~
|
---|
1152 |
|
---|
1153 | Left-aligns the value in a field of a given width.
|
---|
1154 |
|
---|
1155 | **Argument:** field size
|
---|
1156 |
|
---|
1157 | lower
|
---|
1158 | ~~~~~
|
---|
1159 |
|
---|
1160 | Converts a string into all lowercase.
|
---|
1161 |
|
---|
1162 | make_list
|
---|
1163 | ~~~~~~~~~
|
---|
1164 |
|
---|
1165 | Returns the value turned into a list. For an integer, it's a list of
|
---|
1166 | digits. For a string, it's a list of characters.
|
---|
1167 |
|
---|
1168 | phone2numeric
|
---|
1169 | ~~~~~~~~~~~~~
|
---|
1170 |
|
---|
1171 | Converts a phone number (possibly containing letters) to its numerical
|
---|
1172 | equivalent. For example, ``'800-COLLECT'`` will be converted to
|
---|
1173 | ``'800-2655328'``.
|
---|
1174 |
|
---|
1175 | The input doesn't have to be a valid phone number. This will happily convert
|
---|
1176 | any string.
|
---|
1177 |
|
---|
1178 | pluralize
|
---|
1179 | ~~~~~~~~~
|
---|
1180 |
|
---|
1181 | Returns a plural suffix if the value is not 1. By default, this suffix is ``'s'``.
|
---|
1182 |
|
---|
1183 | Example::
|
---|
1184 |
|
---|
1185 | You have {{ num_messages }} message{{ num_messages|pluralize }}.
|
---|
1186 |
|
---|
1187 | For words that require a suffix other than ``'s'``, you can provide an alternate
|
---|
1188 | suffix as a parameter to the filter.
|
---|
1189 |
|
---|
1190 | Example::
|
---|
1191 |
|
---|
1192 | You have {{ num_walruses }} walrus{{ num_walrus|pluralize:"es" }}.
|
---|
1193 |
|
---|
1194 | For words that don't pluralize by simple suffix, you can specify both a
|
---|
1195 | singular and plural suffix, separated by a comma.
|
---|
1196 |
|
---|
1197 | Example::
|
---|
1198 |
|
---|
1199 | You have {{ num_cherries }} cherr{{ num_cherries|pluralize:"y,ies" }}.
|
---|
1200 |
|
---|
1201 | pprint
|
---|
1202 | ~~~~~~
|
---|
1203 |
|
---|
1204 | A wrapper around pprint.pprint -- for debugging, really.
|
---|
1205 |
|
---|
1206 | random
|
---|
1207 | ~~~~~~
|
---|
1208 |
|
---|
1209 | Returns a random item from the list.
|
---|
1210 |
|
---|
1211 | removetags
|
---|
1212 | ~~~~~~~~~~
|
---|
1213 |
|
---|
1214 | Removes a space separated list of [X]HTML tags from the output.
|
---|
1215 |
|
---|
1216 | rjust
|
---|
1217 | ~~~~~
|
---|
1218 |
|
---|
1219 | Right-aligns the value in a field of a given width.
|
---|
1220 |
|
---|
1221 | **Argument:** field size
|
---|
1222 |
|
---|
1223 | slice
|
---|
1224 | ~~~~~
|
---|
1225 |
|
---|
1226 | Returns a slice of the list.
|
---|
1227 |
|
---|
1228 | Uses the same syntax as Python's list slicing. See
|
---|
1229 | http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice
|
---|
1230 | for an introduction.
|
---|
1231 |
|
---|
1232 | Example: ``{{ some_list|slice:":2" }}``
|
---|
1233 |
|
---|
1234 | slugify
|
---|
1235 | ~~~~~~~
|
---|
1236 |
|
---|
1237 | Converts to lowercase, removes non-word characters (alphanumerics and
|
---|
1238 | underscores) and converts spaces to hyphens. Also strips leading and trailing
|
---|
1239 | whitespace.
|
---|
1240 |
|
---|
1241 | stringformat
|
---|
1242 | ~~~~~~~~~~~~
|
---|
1243 |
|
---|
1244 | Formats the variable according to the argument, a string formatting specifier.
|
---|
1245 | This specifier uses Python string formating syntax, with the exception that
|
---|
1246 | the leading "%" is dropped.
|
---|
1247 |
|
---|
1248 | See http://docs.python.org/lib/typesseq-strings.html for documentation of
|
---|
1249 | Python string formatting
|
---|
1250 |
|
---|
1251 | striptags
|
---|
1252 | ~~~~~~~~~
|
---|
1253 |
|
---|
1254 | Strips all [X]HTML tags.
|
---|
1255 |
|
---|
1256 | time
|
---|
1257 | ~~~~
|
---|
1258 |
|
---|
1259 | Formats a time according to the given format (same as the `now`_ tag).
|
---|
1260 | The time filter will only accept parameters in the format string that relate
|
---|
1261 | to the time of day, not the date (for obvious reasons). If you need to
|
---|
1262 | format a date, use the `date`_ filter.
|
---|
1263 |
|
---|
1264 | timesince
|
---|
1265 | ~~~~~~~~~
|
---|
1266 |
|
---|
1267 | Formats a date as the time since that date (i.e. "4 days, 6 hours").
|
---|
1268 |
|
---|
1269 | Takes an optional argument that is a variable containing the date to use as
|
---|
1270 | the comparison point (without the argument, the comparison point is *now*).
|
---|
1271 | For example, if ``blog_date`` is a date instance representing midnight on 1
|
---|
1272 | June 2006, and ``comment_date`` is a date instance for 08:00 on 1 June 2006,
|
---|
1273 | then ``{{ comment_date|timesince:blog_date }}`` would return "8 hours".
|
---|
1274 |
|
---|
1275 | timeuntil
|
---|
1276 | ~~~~~~~~~
|
---|
1277 |
|
---|
1278 | Similar to ``timesince``, except that it measures the time from now until the
|
---|
1279 | given date or datetime. For example, if today is 1 June 2006 and
|
---|
1280 | ``conference_date`` is a date instance holding 29 June 2006, then
|
---|
1281 | ``{{ conference_date|timeuntil }}`` will return "28 days".
|
---|
1282 |
|
---|
1283 | Takes an optional argument that is a variable containing the date to use as
|
---|
1284 | the comparison point (instead of *now*). If ``from_date`` contains 22 June
|
---|
1285 | 2006, then ``{{ conference_date|timeuntil:from_date }}`` will return "7 days".
|
---|
1286 |
|
---|
1287 | title
|
---|
1288 | ~~~~~
|
---|
1289 |
|
---|
1290 | Converts a string into titlecase.
|
---|
1291 |
|
---|
1292 | truncatewords
|
---|
1293 | ~~~~~~~~~~~~~
|
---|
1294 |
|
---|
1295 | Truncates a string after a certain number of words.
|
---|
1296 |
|
---|
1297 | **Argument:** Number of words to truncate after
|
---|
1298 |
|
---|
1299 | truncatewords_html
|
---|
1300 | ~~~~~~~~~~~~~~~~~~
|
---|
1301 |
|
---|
1302 | Similar to ``truncatewords``, except that it is aware of HTML tags. Any tags
|
---|
1303 | that are opened in the string and not closed before the truncation point, are
|
---|
1304 | closed immediately after the truncation.
|
---|
1305 |
|
---|
1306 | This is less efficient than ``truncatewords``, so should only be used when it
|
---|
1307 | is being passed HTML text.
|
---|
1308 |
|
---|
1309 | unordered_list
|
---|
1310 | ~~~~~~~~~~~~~~
|
---|
1311 |
|
---|
1312 | Recursively takes a self-nested list and returns an HTML unordered list --
|
---|
1313 | WITHOUT opening and closing <ul> tags.
|
---|
1314 |
|
---|
1315 | **Changed in Django development version**
|
---|
1316 |
|
---|
1317 | The format accepted by ``unordered_list`` has changed to an easier to
|
---|
1318 | understand format.
|
---|
1319 |
|
---|
1320 | The list is assumed to be in the proper format. For example, if ``var`` contains
|
---|
1321 | ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then
|
---|
1322 | ``{{ var|unordered_list }}`` would return::
|
---|
1323 |
|
---|
1324 | <li>States
|
---|
1325 | <ul>
|
---|
1326 | <li>Kansas
|
---|
1327 | <ul>
|
---|
1328 | <li>Lawrence</li>
|
---|
1329 | <li>Topeka</li>
|
---|
1330 | </ul>
|
---|
1331 | </li>
|
---|
1332 | <li>Illinois</li>
|
---|
1333 | </ul>
|
---|
1334 | </li>
|
---|
1335 |
|
---|
1336 | Note: the previous more restrictive and verbose format is still supported:
|
---|
1337 | ``['States', [['Kansas', [['Lawrence', []], ['Topeka', []]]], ['Illinois', []]]]``,
|
---|
1338 |
|
---|
1339 | upper
|
---|
1340 | ~~~~~
|
---|
1341 |
|
---|
1342 | Converts a string into all uppercase.
|
---|
1343 |
|
---|
1344 | urlencode
|
---|
1345 | ~~~~~~~~~
|
---|
1346 |
|
---|
1347 | Escapes a value for use in a URL.
|
---|
1348 |
|
---|
1349 | urlize
|
---|
1350 | ~~~~~~
|
---|
1351 |
|
---|
1352 | Converts URLs in plain text into clickable links.
|
---|
1353 |
|
---|
1354 | Note that if ``urlize`` is applied to text that already contains HTML markup,
|
---|
1355 | things won't work as expected. Apply this filter only to *plain* text.
|
---|
1356 |
|
---|
1357 | urlizetrunc
|
---|
1358 | ~~~~~~~~~~~
|
---|
1359 |
|
---|
1360 | Converts URLs into clickable links, truncating URLs longer than the given
|
---|
1361 | character limit.
|
---|
1362 |
|
---|
1363 | As with urlize_, this filter should only be applied to *plain* text.
|
---|
1364 |
|
---|
1365 | **Argument:** Length to truncate URLs to
|
---|
1366 |
|
---|
1367 | wordcount
|
---|
1368 | ~~~~~~~~~
|
---|
1369 |
|
---|
1370 | Returns the number of words.
|
---|
1371 |
|
---|
1372 | wordwrap
|
---|
1373 | ~~~~~~~~
|
---|
1374 |
|
---|
1375 | Wraps words at specified line length.
|
---|
1376 |
|
---|
1377 | **Argument:** number of characters at which to wrap the text
|
---|
1378 |
|
---|
1379 | yesno
|
---|
1380 | ~~~~~
|
---|
1381 |
|
---|
1382 | Given a string mapping values for true, false and (optionally) None,
|
---|
1383 | returns one of those strings according to the value:
|
---|
1384 |
|
---|
1385 | ========== ====================== ==================================
|
---|
1386 | Value Argument Outputs
|
---|
1387 | ========== ====================== ==================================
|
---|
1388 | ``True`` ``"yeah,no,maybe"`` ``yeah``
|
---|
1389 | ``False`` ``"yeah,no,maybe"`` ``no``
|
---|
1390 | ``None`` ``"yeah,no,maybe"`` ``maybe``
|
---|
1391 | ``None`` ``"yeah,no"`` ``"no"`` (converts None to False
|
---|
1392 | if no mapping for None is given)
|
---|
1393 | ========== ====================== ==================================
|
---|
1394 |
|
---|
1395 | Other tags and filter libraries
|
---|
1396 | ===============================
|
---|
1397 |
|
---|
1398 | Django comes with a couple of other template-tag libraries that you have to
|
---|
1399 | enable explicitly in your ``INSTALLED_APPS`` setting and enable in your
|
---|
1400 | template with the ``{% load %}`` tag.
|
---|
1401 |
|
---|
1402 | django.contrib.humanize
|
---|
1403 | -----------------------
|
---|
1404 |
|
---|
1405 | A set of Django template filters useful for adding a "human touch" to data. See
|
---|
1406 | the `humanize documentation`_.
|
---|
1407 |
|
---|
1408 | .. _humanize documentation: ../add_ons/#humanize
|
---|
1409 |
|
---|
1410 | django.contrib.markup
|
---|
1411 | ---------------------
|
---|
1412 |
|
---|
1413 | A collection of template filters that implement these common markup languages:
|
---|
1414 |
|
---|
1415 | * Textile
|
---|
1416 | * Markdown
|
---|
1417 | * ReST (ReStructured Text)
|
---|
1418 |
|
---|
1419 | django.contrib.webdesign
|
---|
1420 | ------------------------
|
---|
1421 |
|
---|
1422 | A collection of template tags that can be useful while designing a website,
|
---|
1423 | such as a generator of Lorem Ipsum text. See the `webdesign documentation`_.
|
---|
1424 |
|
---|
1425 | .. _webdesign documentation: ../webdesign/
|
---|
1426 |
|
---|
1427 | Next steps
|
---|
1428 | ==========
|
---|
1429 |
|
---|
1430 | Read the document `The Django template language: For Python programmers`_ if
|
---|
1431 | you're interested in learning the template system from a technical
|
---|
1432 | perspective -- how it works and how to extend it.
|
---|
1433 |
|
---|
1434 | .. _The Django template language\: For Python programmers: ../templates_python/
|
---|