Ticket #5340: templates.txt

File templates.txt, 45.2 KB (added by justinlilly@…, 17 years ago)

Proposed patch to fix the escaping issue causing the bug

Line 
1==================================================
2The Django template language: For template authors
3==================================================
4
5Django's template language is designed to strike a balance between power and
6ease. It's designed to feel comfortable to those used to working with HTML. If
7you have any exposure to other text-based template languages, such as Smarty_
8or 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
13Templates
14=========
15
16A template is simply a text file. It can generate any text-based format (HTML,
17XML, CSV, etc.).
18
19A template contains **variables**, which get replaced with values when the
20template is evaluated, and **tags**, which control the logic of the template.
21
22Below is a minimal template that illustrates a few basics. Each element will be
23explained 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
52Variables
53=========
54
55Variables look like this: ``{{ variable }}``. When the template engine
56encounters a variable, it evaluates that variable and replaces it with the
57result.
58
59Use 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
71In the above example, ``{{ section.title }}`` will be replaced with the
72``title`` attribute of the ``section`` object.
73
74If you use a variable that doesn't exist, the template system will insert
75the value of the ``TEMPLATE_STRING_IF_INVALID`` setting, which is set to ``''``
76(the empty string) by default.
77
78See `Using the built-in reference`_, below, for help on finding what variables
79are available in a given template.
80
81Filters
82=======
83
84You can modify variables for display by using **filters**.
85
86Filters look like this: ``{{ name|lower }}``. This displays the value of the
87``{{ name }}`` variable after being filtered through the ``lower`` filter,
88which converts text to lowercase. Use a pipe (``|``) to apply a filter.
89
90Filters 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,
92then converting line breaks to ``<p>`` tags.
93
94Some filters take arguments. A filter argument looks like this: ``{{
95bio|truncatewords:30 }}``. This will display the first 30 words of the ``bio``
96variable.
97
98Filter arguments that contain spaces must be quoted; for example, to join a list
99with commas and spaced you'd use ``{{ list|join:", " }}``.
100
101The `Built-in filter reference`_ below describes all the built-in filters.
102
103Tags
104====
105
106Tags look like this: ``{% tag %}``. Tags are more complex than variables: Some
107create text in the output, some control flow by performing loops or logic, and
108some load external information into the template to be used by later variables.
109
110Some tags require beginning and ending tags (i.e.
111``{% tag %} ... tag contents ... {% endtag %}``). The `Built-in tag reference`_
112below describes all the built-in tags. You can create your own tags, if you
113know how to write Python code.
114
115Comments
116========
117
118To comment-out part of a line in a template, use the comment syntax: ``{# #}``.
119
120For example, this template would render as ``'hello'``::
121
122 {# greeting #}hello
123
124A comment can contain any template code, invalid or not. For example::
125
126 {# {% if foo %}bar{% else %} #}
127
128This syntax can only be used for single-line comments (no newlines are
129permitted between the ``{#`` and ``#}`` delimiters). If you need to comment
130out a multiline portion of the template, see the ``comment`` tag, below__.
131
132__ comment_
133
134Template inheritance
135====================
136
137The most powerful -- and thus the most complex -- part of Django's template
138engine is template inheritance. Template inheritance allows you to build a base
139"skeleton" template that contains all the common elements of your site and
140defines **blocks** that child templates can override.
141
142It'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
168This template, which we'll call ``base.html``, defines a simple HTML skeleton
169document 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
172In this example, the ``{% block %}`` tag defines three blocks that child
173templates can fill in. All the ``block`` tag does is to tell the template
174engine that a child template may override those portions of the template.
175
176A 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
189The ``{% extends %}`` tag is the key here. It tells the template engine that
190this template "extends" another template. When the template system evaluates
191this template, first it locates the parent -- in this case, "base.html".
192
193At that point, the template engine will notice the three ``{% block %}`` tags
194in ``base.html`` and replace those blocks with the contents of the child
195template. Depending on the value of ``blog_entries``, the output might look
196like::
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
224Note that since the child template didn't define the ``sidebar`` block, the
225value from the parent template is used instead. Content within a ``{% block %}``
226tag in a parent template is always used as a fallback.
227
228You can use as many levels of inheritance as needed. One common way of using
229inheritance 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
241This approach maximizes code reuse and makes it easy to add items to shared
242content areas, such as section-wide navigation.
243
244Here 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
273Finally, note that you can't define multiple ``{% block %}`` tags with the same
274name 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 --
276it also defines the content that fills the hole in the *parent*. If there were
277two similarly-named ``{% block %}`` tags in a template, that template's parent
278wouldn't know which one of the blocks' content to use.
279
280Using the built-in reference
281============================
282
283Django's admin interface includes a complete reference of all template tags and
284filters available for a given site. To see it, go to your admin interface and
285click the "Documentation" link in the upper right of the page.
286
287The reference is divided into 4 sections: tags, filters, models, and views.
288
289The **tags** and **filters** sections describe all the built-in tags (in fact,
290the tag and filter references below come directly from those pages) as well as
291any custom tag or filter libraries available.
292
293The **views** page is the most valuable. Each URL in your site has a separate
294entry 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
301Each view documentation page also has a bookmarklet that you can use to jump
302from any page to the documentation page for that view.
303
304Because Django-powered sites usually use database objects, the **models**
305section of the documentation page describes each type of object in the system
306along with all the fields available on that object.
307
308Taken together, the documentation pages should tell you every tag, filter,
309variable and object available to you in a given template.
310
311Custom tag and filter libraries
312===============================
313
314Certain applications provide custom tag and filter libraries. To access them in
315a template, use the ``{% load %}`` tag::
316
317 {% load comments %}
318
319 {% comment_form for blogs.entries entry.id with is_public yes %}
320
321In the above, the ``load`` tag loads the ``comments`` tag library, which then
322makes the ``comment_form`` tag available for use. Consult the documentation
323area in your admin to find the list of custom libraries in your installation.
324
325The ``{% load %}`` tag can take multiple library names, separated by spaces.
326Example::
327
328 {% load comments i18n %}
329
330Custom libraries and template inheritance
331-----------------------------------------
332
333When you load a custom tag or filter library, the tags/filters are only made
334available to the current template -- not any parent or child templates along
335the template-inheritance path.
336
337For example, if a template ``foo.html`` has ``{% load comments %}``, a child
338template (e.g., one that has ``{% extends "foo.html" %}``) will *not* have
339access to the comments template tags and filters. The child template is
340responsible for its own ``{% load comments %}``.
341
342This is a feature for the sake of maintainability and sanity.
343
344Built-in tag and filter reference
345=================================
346
347For those without an admin site available, reference for the stock tags and
348filters follows. Because Django is highly customizable, the reference in your
349admin should be considered the final word on what tags and filters are
350available, and what they do.
351
352Built-in tag reference
353----------------------
354
355block
356~~~~~
357
358Define a block that can be overridden by child templates. See
359`Template inheritance`_ for more information.
360
361comment
362~~~~~~~
363
364Ignore everything between ``{% comment %}`` and ``{% endcomment %}``
365
366cycle
367~~~~~
368
369**Changed in Django development version**
370Cycle among the given strings or variables each time this tag is encountered.
371
372Within a loop, cycles among the given strings/variables each time through the
373loop::
374
375 {% for o in some_list %}
376 <tr class="{% cycle 'row1' 'row2' rowvar %}">
377 ...
378 </tr>
379 {% endfor %}
380
381Outside of a loop, give the values a unique name the first time you call it,
382then 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
388You can use any number of values, separated by spaces. Values enclosed in
389single (') or double quotes (") are treated as string literals, while values
390without quotes are assumed to refer to context variables.
391
392You can also separate values with commas::
393
394 {% cycle row1,row2,row3 %}
395
396In this syntax, each value will be interpreted as literal text. The
397comma-based syntax exists for backwards-compatibility, and should not be
398used for new projects.
399
400debug
401~~~~~
402
403Output a whole load of debugging information, including the current context and
404imported modules.
405
406extends
407~~~~~~~
408
409Signal that this template extends a parent template.
410
411This 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
421See `Template inheritance`_ for more information.
422
423filter
424~~~~~~
425
426Filter the contents of the variable through variable filters.
427
428Filters can also be piped through each other, and they can have arguments --
429just like in variable syntax.
430
431Sample usage::
432
433 {% filter escape|lower %}
434 This text will be HTML-escaped, and will appear in all lowercase.
435 {% endfilter %}
436
437firstof
438~~~~~~~
439
440Outputs the first variable passed that is not False. Outputs nothing if all the
441passed variables are False.
442
443Sample usage::
444
445 {% firstof var1 var2 var3 %}
446
447This 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
457for
458~~~
459
460Loop over each item in an array. For example, to display a list of athletes
461provided in ``athlete_list``::
462
463 <ul>
464 {% for athlete in athlete_list %}
465 <li>{{ athlete.name }}</li>
466 {% endfor %}
467 </ul>
468
469You can loop over a list in reverse by using ``{% for obj in list reversed %}``.
470
471**New in Django development version**
472If you need to loop over a list of lists, you can unpack the values
473in eachs sub-list into a set of known names. For example, if your context contains
474a list of (x,y) coordinates called ``points``, you could use the following
475to output the list of points::
476
477 {% for x, y in points %}
478 There is a point at {{ x }},{{ y }}
479 {% endfor %}
480
481This can also be useful if you need to access the items in a dictionary.
482For example, if your context contained a dictionary ``data``, the following
483would display the keys and values of the dictionary::
484
485 {% for key, value in data.items %}
486 {{ key }}: {{ value }}
487 {% endfor %}
488
489The 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
506if
507~~
508
509The ``{% if %}`` tag evaluates a variable, and if that variable is "true" (i.e.
510exists, is not empty, and is not a false boolean value) the contents of the
511block are output::
512
513 {% if athlete_list %}
514 Number of athletes: {{ athlete_list|length }}
515 {% else %}
516 No athletes.
517 {% endif %}
518
519In the above, if ``athlete_list`` is not empty, the number of athletes will be
520displayed by the ``{{ athlete_list|length }}`` variable.
521
522As you can see, the ``if`` tag can take an optional ``{% else %}`` clause that
523will be displayed if the test fails.
524
525``if`` tags may use ``and``, ``or`` or ``not`` to test a number of variables or
526to 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
551the order of logic would be ambiguous. For example, this is invalid::
552
553 {% if athlete_list and coach_list or cheerleader_list %}
554
555If 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
564Multiple uses of the same logical operator are fine, as long as you use the
565same operator. For example, this is valid::
566
567 {% if athlete_list or coach_list or parent_list or teacher_list %}
568
569ifchanged
570~~~~~~~~~
571
572Check if a value has changed from the last iteration of a loop.
573
574The 'ifchanged' block tag is used within a loop. It has two possible uses.
575
5761. 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
5872. 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
598ifequal
599~~~~~~~
600
601Output the contents of the block if the two arguments equal each other.
602
603Example::
604
605 {% ifequal user.id comment.user_id %}
606 ...
607 {% endifequal %}
608
609As in the ``{% if %}`` tag, an ``{% else %}`` clause is optional.
610
611The arguments can be hard-coded strings, so the following is valid::
612
613 {% ifequal user.username "adrian" %}
614 ...
615 {% endifequal %}
616
617It is only possible to compare an argument to template variables or strings.
618You 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``
620tag instead.
621
622ifnotequal
623~~~~~~~~~~
624
625Just like ``ifequal``, except it tests that the two arguments are not equal.
626
627include
628~~~~~~~
629
630Loads a template and renders it with the current context. This is a way of
631"including" other templates within a template.
632
633The template name can either be a variable or a hard-coded (quoted) string,
634in either single or double quotes.
635
636This example includes the contents of the template ``"foo/bar.html"``::
637
638 {% include "foo/bar.html" %}
639
640This example includes the contents of the template whose name is contained in
641the variable ``template_name``::
642
643 {% include template_name %}
644
645An included template is rendered with the context of the template that's
646including 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
657See also: ``{% ssi %}``.
658
659load
660~~~~
661
662Load a custom template tag set.
663
664See `Custom tag and filter libraries`_ for more information.
665
666now
667~~~
668
669Display the date, formatted according to the given string.
670
671Uses the same format as PHP's ``date()`` function (http://php.net/date)
672with some custom extensions.
673
674Available 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
736Example::
737
738 It is {% now "jS F Y H:i" %}
739
740Note 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
743escaped, because it's not a format character::
744
745 It is the {% now "jS o\f F" %}
746
747This would display as "It is the 4th of September".
748
749regroup
750~~~~~~~
751
752Regroup a list of alike objects by a common attribute.
753
754This complex tag is best illustrated by use of an example: say that ``people``
755is 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,
767like this:
768
769 * Male:
770 * George Bush
771 * Bill Clinton
772 * Female:
773 * Margaret Thatcher
774 * Condoleezza Rice
775 * Unknown:
776 * Pat Smith
777
778You can use the ``{% regroup %}`` tag to group the list of people by gender.
779The 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
795Let's walk through this example. ``{% regroup %}`` takes three arguments: the
796list you want to regroup, the attribute to group by, and the name of the
797resulting list. Here, we're regrouping the ``people`` list by the ``gender``
798attribute 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
808Note that ``{% regroup %}`` does not order its input! Our example relies on
809the fact that the ``people`` list was ordered by ``gender`` in the first place.
810If the ``people`` list did *not* order its members by ``gender``, the regrouping
811would naively display more than one group for a single gender. For example,
812say the ``people`` list was set to this (note that the males are not grouped
813together)::
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
823With this input for ``people``, the example ``{% regroup %}`` template code
824above 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
837The easiest solution to this gotcha is to make sure in your view code that the
838data is ordered according to how you want to display it.
839
840Another solution is to sort the data in the template using the ``dictsort``
841filter, if your data is in a list of dictionaries::
842
843 {% regroup people|dictsort:"gender" by gender as gender_list %}
844
845spaceless
846~~~~~~~~~
847
848Removes whitespace between HTML tags. This includes tab
849characters and newlines.
850
851Example usage::
852
853 {% spaceless %}
854 <p>
855 <a href="foo/">Foo</a>
856 </p>
857 {% endspaceless %}
858
859This example would return this HTML::
860
861 <p><a href="foo/">Foo</a></p>
862
863Only space between *tags* is removed -- not space between tags and text. In
864this example, the space around ``Hello`` won't be stripped::
865
866 {% spaceless %}
867 <strong>
868 Hello
869 </strong>
870 {% endspaceless %}
871
872ssi
873~~~
874
875Output the contents of a given file into the page.
876
877Like a simple "include" tag, ``{% ssi %}`` includes the contents of another
878file -- which must be specified using an absolute path -- in the current
879page::
880
881 {% ssi /home/html/ljworld.com/includes/right_generic.html %}
882
883If the optional "parsed" parameter is given, the contents of the included
884file are evaluated as template code, within the current context::
885
886 {% ssi /home/html/ljworld.com/includes/right_generic.html parsed %}
887
888Note that if you use ``{% ssi %}``, you'll need to define
889`ALLOWED_INCLUDE_ROOTS`_ in your Django settings, as a security measure.
890
891See also: ``{% include %}``.
892
893.. _ALLOWED_INCLUDE_ROOTS: ../settings/#allowed-include-roots
894
895templatetag
896~~~~~~~~~~~
897
898Output one of the syntax characters used to compose template tags.
899
900Since the template system has no concept of "escaping", to display one of the
901bits used in template tags, you must use the ``{% templatetag %}`` tag.
902
903The 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
918url
919~~~
920
921**Note that the syntax for this tag may change in the future, as we make it more robust.**
922
923Returns an absolute URL (i.e., a URL without the domain name) matching a given
924view function and optional parameters. This is a way to output links without
925violating the DRY principle by having to hard-code URLs in your templates::
926
927 {% url path.to.some_view arg1,arg2,name1=value1 %}
928
929The first argument is a path to a view function in the format
930``package.package.module.function``. Additional arguments are optional and
931should be comma-separated values that will be used as positional and keyword
932arguments in the URL. All arguments required by the URLconf should be present.
933
934For example, suppose you have a view, ``app_views.client``, whose URLconf
935takes 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
940If this app's URLconf is included into the project's URLconf under a path
941such 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
949The template tag will output the string ``/clients/client/123/``.
950
951**New in development version:** If you're using `named URL patterns`_,
952you can refer to the name of the pattern in the ``url`` tag instead of
953using the path to the view.
954
955.. _named URL patterns: ../url_dispatch/#naming-url-patterns
956
957widthratio
958~~~~~~~~~~
959
960For creating bar charts and such, this tag calculates the ratio of a given value
961to a maximum value, and then applies that ratio to a constant.
962
963For example::
964
965 <img src="bar.gif" height="10" width="{% widthratio this_value max_value 100 %}" />
966
967Above, if ``this_value`` is 175 and ``max_value`` is 200, the the image in the
968above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5
969which is rounded up to 88).
970
971with
972~~~~
973
974**New in Django development version**
975
976Caches a complex variable under a simpler name. This is useful when accessing
977an "expensive" method (e.g., one that hits the database) multiple times.
978
979For example::
980
981 {% with business.employees.count as total %}
982 {{ total }} employee{{ total|pluralize }}
983 {% endwith %}
984
985The populated variable (in the example above, ``total``) is only available
986between the ``{% with %}`` and ``{% endwith %}`` tags.
987
988Built-in filter reference
989-------------------------
990
991add
992~~~
993
994Adds the arg to the value.
995
996addslashes
997~~~~~~~~~~
998
999Adds slashes. Useful for passing strings to JavaScript, for example.
1000
1001
1002capfirst
1003~~~~~~~~
1004
1005Capitalizes the first character of the value.
1006
1007center
1008~~~~~~
1009
1010Centers the value in a field of a given width.
1011
1012cut
1013~~~
1014
1015Removes all values of arg from the given string.
1016
1017date
1018~~~~
1019
1020Formats a date according to the given format (same as the `now`_ tag).
1021
1022default
1023~~~~~~~
1024
1025If value is unavailable, use given default.
1026
1027default_if_none
1028~~~~~~~~~~~~~~~
1029
1030If value is ``None``, use given default.
1031
1032dictsort
1033~~~~~~~~
1034
1035Takes a list of dictionaries, returns that list sorted by the key given in
1036the argument.
1037
1038dictsortreversed
1039~~~~~~~~~~~~~~~~
1040
1041Takes a list of dictionaries, returns that list sorted in reverse order by the
1042key given in the argument.
1043
1044divisibleby
1045~~~~~~~~~~~
1046
1047Returns true if the value is divisible by the argument.
1048
1049escape
1050~~~~~~
1051
1052Escapes a string's HTML. Specifically, it makes these replacements:
1053
1054 * ``"&"`` to ``"&amp;"``
1055 * ``<`` to ``"&lt;"``
1056 * ``>`` to ``"&gt;"``
1057 * ``'"'`` (double quote) to ``'&quot;'``
1058 * ``"'"`` (single quote) to ``'&#39;'``
1059
1060filesizeformat
1061~~~~~~~~~~~~~~
1062
1063Format the value like a 'human-readable' file size (i.e. ``'13 KB'``,
1064``'4.1 MB'``, ``'102 bytes'``, etc).
1065
1066first
1067~~~~~
1068
1069Returns the first item in a list.
1070
1071fix_ampersands
1072~~~~~~~~~~~~~~
1073
1074Replaces ampersands with ``&amp;`` entities.
1075
1076floatformat
1077~~~~~~~~~~~
1078
1079When used without an argument, rounds a floating-point number to one decimal
1080place -- 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
1086If used with a numeric integer argument, ``floatformat`` rounds a number to that
1087many 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
1092If the argument passed to ``floatformat`` is negative, it will round a number to
1093that many decimal places -- but only if there's a decimal part to be displayed.
1094For example:
1095
1096 * ``36.1234`` with floatformat:-3 gets converted to ``36.123``
1097 * ``36`` with floatformat:-4 gets converted to ``36``
1098
1099Using ``floatformat`` with no argument is equivalent to using ``floatformat`` with
1100an argument of ``-1``.
1101
1102get_digit
1103~~~~~~~~~
1104
1105Given a whole number, returns the requested digit of it, where 1 is the
1106right-most digit, 2 is the second-right-most digit, etc. Returns the original
1107value for invalid input (if input or argument is not an integer, or if argument
1108is less than 1). Otherwise, output is always an integer.
1109
1110iriencode
1111~~~~~~~~~
1112
1113Converts an IRI (Internationalized Resource Identifier) to a string that is
1114suitable for including in a URL. This is necessary if you're trying to use
1115strings containing non-ASCII characters in a URL.
1116
1117It's safe to use this filter on a string that has already gone through the
1118``urlencode`` filter.
1119
1120join
1121~~~~
1122
1123Joins a list with a string, like Python's ``str.join(list)``.
1124
1125length
1126~~~~~~
1127
1128Returns the length of the value. Useful for lists.
1129
1130length_is
1131~~~~~~~~~
1132
1133Returns a boolean of whether the value's length is the argument.
1134
1135linebreaks
1136~~~~~~~~~~
1137
1138Converts newlines into ``<p>`` and ``<br />`` tags.
1139
1140linebreaksbr
1141~~~~~~~~~~~~
1142
1143Converts newlines into ``<br />`` tags.
1144
1145linenumbers
1146~~~~~~~~~~~
1147
1148Displays text with line numbers.
1149
1150ljust
1151~~~~~
1152
1153Left-aligns the value in a field of a given width.
1154
1155**Argument:** field size
1156
1157lower
1158~~~~~
1159
1160Converts a string into all lowercase.
1161
1162make_list
1163~~~~~~~~~
1164
1165Returns the value turned into a list. For an integer, it's a list of
1166digits. For a string, it's a list of characters.
1167
1168phone2numeric
1169~~~~~~~~~~~~~
1170
1171Converts a phone number (possibly containing letters) to its numerical
1172equivalent. For example, ``'800-COLLECT'`` will be converted to
1173``'800-2655328'``.
1174
1175The input doesn't have to be a valid phone number. This will happily convert
1176any string.
1177
1178pluralize
1179~~~~~~~~~
1180
1181Returns a plural suffix if the value is not 1. By default, this suffix is ``'s'``.
1182
1183Example::
1184
1185 You have {{ num_messages }} message{{ num_messages|pluralize }}.
1186
1187For words that require a suffix other than ``'s'``, you can provide an alternate
1188suffix as a parameter to the filter.
1189
1190Example::
1191
1192 You have {{ num_walruses }} walrus{{ num_walrus|pluralize:"es" }}.
1193
1194For words that don't pluralize by simple suffix, you can specify both a
1195singular and plural suffix, separated by a comma.
1196
1197Example::
1198
1199 You have {{ num_cherries }} cherr{{ num_cherries|pluralize:"y,ies" }}.
1200
1201pprint
1202~~~~~~
1203
1204A wrapper around pprint.pprint -- for debugging, really.
1205
1206random
1207~~~~~~
1208
1209Returns a random item from the list.
1210
1211removetags
1212~~~~~~~~~~
1213
1214Removes a space separated list of [X]HTML tags from the output.
1215
1216rjust
1217~~~~~
1218
1219Right-aligns the value in a field of a given width.
1220
1221**Argument:** field size
1222
1223slice
1224~~~~~
1225
1226Returns a slice of the list.
1227
1228Uses the same syntax as Python's list slicing. See
1229http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice
1230for an introduction.
1231
1232Example: ``{{ some_list|slice:":2" }}``
1233
1234slugify
1235~~~~~~~
1236
1237Converts to lowercase, removes non-word characters (alphanumerics and
1238underscores) and converts spaces to hyphens. Also strips leading and trailing
1239whitespace.
1240
1241stringformat
1242~~~~~~~~~~~~
1243
1244Formats the variable according to the argument, a string formatting specifier.
1245This specifier uses Python string formating syntax, with the exception that
1246the leading "%" is dropped.
1247
1248See http://docs.python.org/lib/typesseq-strings.html for documentation of
1249Python string formatting
1250
1251striptags
1252~~~~~~~~~
1253
1254Strips all [X]HTML tags.
1255
1256time
1257~~~~
1258
1259Formats a time according to the given format (same as the `now`_ tag).
1260The time filter will only accept parameters in the format string that relate
1261to the time of day, not the date (for obvious reasons). If you need to
1262format a date, use the `date`_ filter.
1263
1264timesince
1265~~~~~~~~~
1266
1267Formats a date as the time since that date (i.e. "4 days, 6 hours").
1268
1269Takes an optional argument that is a variable containing the date to use as
1270the comparison point (without the argument, the comparison point is *now*).
1271For example, if ``blog_date`` is a date instance representing midnight on 1
1272June 2006, and ``comment_date`` is a date instance for 08:00 on 1 June 2006,
1273then ``{{ comment_date|timesince:blog_date }}`` would return "8 hours".
1274
1275timeuntil
1276~~~~~~~~~
1277
1278Similar to ``timesince``, except that it measures the time from now until the
1279given 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
1283Takes an optional argument that is a variable containing the date to use as
1284the comparison point (instead of *now*). If ``from_date`` contains 22 June
12852006, then ``{{ conference_date|timeuntil:from_date }}`` will return "7 days".
1286
1287title
1288~~~~~
1289
1290Converts a string into titlecase.
1291
1292truncatewords
1293~~~~~~~~~~~~~
1294
1295Truncates a string after a certain number of words.
1296
1297**Argument:** Number of words to truncate after
1298
1299truncatewords_html
1300~~~~~~~~~~~~~~~~~~
1301
1302Similar to ``truncatewords``, except that it is aware of HTML tags. Any tags
1303that are opened in the string and not closed before the truncation point, are
1304closed immediately after the truncation.
1305
1306This is less efficient than ``truncatewords``, so should only be used when it
1307is being passed HTML text.
1308
1309unordered_list
1310~~~~~~~~~~~~~~
1311
1312Recursively takes a self-nested list and returns an HTML unordered list --
1313WITHOUT opening and closing <ul> tags.
1314
1315**Changed in Django development version**
1316
1317The format accepted by ``unordered_list`` has changed to an easier to
1318understand format.
1319
1320The 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
1336Note: the previous more restrictive and verbose format is still supported:
1337``['States', [['Kansas', [['Lawrence', []], ['Topeka', []]]], ['Illinois', []]]]``,
1338
1339upper
1340~~~~~
1341
1342Converts a string into all uppercase.
1343
1344urlencode
1345~~~~~~~~~
1346
1347Escapes a value for use in a URL.
1348
1349urlize
1350~~~~~~
1351
1352Converts URLs in plain text into clickable links.
1353
1354Note that if ``urlize`` is applied to text that already contains HTML markup,
1355things won't work as expected. Apply this filter only to *plain* text.
1356
1357urlizetrunc
1358~~~~~~~~~~~
1359
1360Converts URLs into clickable links, truncating URLs longer than the given
1361character limit.
1362
1363As with urlize_, this filter should only be applied to *plain* text.
1364
1365**Argument:** Length to truncate URLs to
1366
1367wordcount
1368~~~~~~~~~
1369
1370Returns the number of words.
1371
1372wordwrap
1373~~~~~~~~
1374
1375Wraps words at specified line length.
1376
1377**Argument:** number of characters at which to wrap the text
1378
1379yesno
1380~~~~~
1381
1382Given a string mapping values for true, false and (optionally) None,
1383returns one of those strings according to the value:
1384
1385========== ====================== ==================================
1386Value 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
1395Other tags and filter libraries
1396===============================
1397
1398Django comes with a couple of other template-tag libraries that you have to
1399enable explicitly in your ``INSTALLED_APPS`` setting and enable in your
1400template with the ``{% load %}`` tag.
1401
1402django.contrib.humanize
1403-----------------------
1404
1405A set of Django template filters useful for adding a "human touch" to data. See
1406the `humanize documentation`_.
1407
1408.. _humanize documentation: ../add_ons/#humanize
1409
1410django.contrib.markup
1411---------------------
1412
1413A collection of template filters that implement these common markup languages:
1414
1415 * Textile
1416 * Markdown
1417 * ReST (ReStructured Text)
1418
1419django.contrib.webdesign
1420------------------------
1421
1422A collection of template tags that can be useful while designing a website,
1423such as a generator of Lorem Ipsum text. See the `webdesign documentation`_.
1424
1425.. _webdesign documentation: ../webdesign/
1426
1427Next steps
1428==========
1429
1430Read the document `The Django template language: For Python programmers`_ if
1431you're interested in learning the template system from a technical
1432perspective -- how it works and how to extend it.
1433
1434.. _The Django template language\: For Python programmers: ../templates_python/
Back to Top