Clarified that urlize and urlizetrunc should only be applied to plain text. Refs...
[django.git] / docs / templates.txt
blob53384864ea7e3cd02985577df8f40d6e728c73c9
1 ==================================================
2 The Django template language: For template authors
3 ==================================================
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.
10 .. _Smarty: http://smarty.php.net/
11 .. _CheetahTemplate: http://www.cheetahtemplate.org/
13 Templates
14 =========
16 A template is simply a text file. It can generate any text-based format (HTML,
17 XML, CSV, etc.).
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.
22 Below is a minimal template that illustrates a few basics. Each element will be
23 explained later in this document.::
25     {% extends "base_generic.html" %}
27     {% block title %}{{ section.title }}{% endblock %}
29     {% block content %}
30     <h1>{{ section.title }}</h1>
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 %}
42 .. admonition:: Philosophy
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.
50     Oh, and one more thing: Making humans edit XML is sadistic!
52 Variables
53 =========
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.
59 Use a dot (``.``) to access attributes of a variable.
61 .. admonition:: Behind the scenes
63     Technically, when the template system encounters a dot, it tries the
64     following lookups, in this order:
66         * Dictionary lookup
67         * Attribute lookup
68         * Method call
69         * List-index lookup
71 In the above example, ``{{ section.title }}`` will be replaced with the
72 ``title`` attribute of the ``section`` object.
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.
78 See `Using the built-in reference`_, below, for help on finding what variables
79 are available in a given template.
81 Filters
82 =======
84 You can modify variables for display by using **filters**.
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.
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.
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.
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:", " }}``.
101 The `Built-in filter reference`_ below describes all the built-in filters.
103 Tags
104 ====
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.
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.
115 Comments
116 ========
118 To comment-out part of a line in a template, use the comment syntax: ``{# #}``.
120 For example, this template would render as ``'hello'``::
122     {# greeting #}hello
124 A comment can contain any template code, invalid or not. For example::
126     {# {% if foo %}bar{% else %} #}
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__.
132 __ comment_
134 Template inheritance
135 ====================
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.
142 It's easiest to understand template inheritance by starting with an example::
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>
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>
162         <div id="content">
163             {% block content %}{% endblock %}
164         </div>
165     </body>
166     </html>
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.
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.
176 A child template might look like this::
178     {% extends "base.html" %}
180     {% block title %}My amazing blog{% endblock %}
182     {% block content %}
183     {% for entry in blog_entries %}
184         <h2>{{ entry.title }}</h2>
185         <p>{{ entry.body }}</p>
186     {% endfor %}
187     {% endblock %}
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".
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::
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>
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>
214         <div id="content">
215             <h2>Entry one</h2>
216             <p>This is my first entry.</p>
218             <h2>Entry two</h2>
219             <p>This is my second entry.</p>
220         </div>
221     </body>
222     </html>
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.
228 You can use as many levels of inheritance as needed. One common way of using
229 inheritance is the following three-level approach:
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.
241 This approach maximizes code reuse and makes it easy to add items to shared
242 content areas, such as section-wide navigation.
244 Here are some tips for working with inheritance:
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.
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.
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.
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.
263     * For extra readability, you can optionally give a *name* to your
264       ``{% endblock %}`` tag. For example::
266           {% block content %}
267           ...
268           {% endblock content %}
270       In larger templates, this technique helps you see which ``{% block %}``
271       tags are being closed.
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.
280 Using the built-in reference
281 ============================
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.
287 The reference is divided into 4 sections: tags, filters, models, and views.
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.
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:
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.
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.
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.
308 Taken together, the documentation pages should tell you every tag, filter,
309 variable and object available to you in a given template.
311 Custom tag and filter libraries
312 ===============================
314 Certain applications provide custom tag and filter libraries. To access them in
315 a template, use the ``{% load %}`` tag::
317     {% load comments %}
319     {% comment_form for blogs.entries entry.id with is_public yes %}
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.
325 The ``{% load %}`` tag can take multiple library names, separated by spaces.
326 Example::
328     {% load comments i18n %}
330 Custom libraries and template inheritance
331 -----------------------------------------
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.
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 %}``.
342 This is a feature for the sake of maintainability and sanity.
344 Built-in tag and filter reference
345 =================================
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.
352 Built-in tag reference
353 ----------------------
355 block
356 ~~~~~
358 Define a block that can be overridden by child templates. See
359 `Template inheritance`_ for more information.
361 comment
362 ~~~~~~~
364 Ignore everything between ``{% comment %}`` and ``{% endcomment %}``
366 cycle
367 ~~~~~
369 Cycle among the given strings each time this tag is encountered.
371 Within a loop, cycles among the given strings each time through the loop::
373     {% for o in some_list %}
374         <tr class="{% cycle row1,row2 %}">
375             ...
376         </tr>
377     {% endfor %}
379 Outside of a loop, give the values a unique name the first time you call it,
380 then use that name each successive time through::
382         <tr class="{% cycle row1,row2,row3 as rowcolors %}">...</tr>
383         <tr class="{% cycle rowcolors %}">...</tr>
384         <tr class="{% cycle rowcolors %}">...</tr>
386 You can use any number of values, separated by commas. Make sure not to put
387 spaces between the values -- only commas.
389 debug
390 ~~~~~
392 Output a whole load of debugging information, including the current context and
393 imported modules.
395 extends
396 ~~~~~~~
398 Signal that this template extends a parent template.
400 This tag can be used in two ways:
402    * ``{% extends "base.html" %}`` (with quotes) uses the literal value
403      ``"base.html"`` as the name of the parent template to extend.
405    * ``{% extends variable %}`` uses the value of ``variable``. If the variable
406      evaluates to a string, Django will use that string as the name of the
407      parent template. If the variable evaluates to a ``Template`` object,
408      Django will use that object as the parent template.
410 See `Template inheritance`_ for more information.
412 filter
413 ~~~~~~
415 Filter the contents of the variable through variable filters.
417 Filters can also be piped through each other, and they can have arguments --
418 just like in variable syntax.
420 Sample usage::
422     {% filter escape|lower %}
423         This text will be HTML-escaped, and will appear in all lowercase.
424     {% endfilter %}
426 firstof
427 ~~~~~~~
429 Outputs the first variable passed that is not False.  Outputs nothing if all the
430 passed variables are False.
432 Sample usage::
434     {% firstof var1 var2 var3 %}
436 This is equivalent to::
438     {% if var1 %}
439         {{ var1 }}
440     {% else %}{% if var2 %}
441         {{ var2 }}
442     {% else %}{% if var3 %}
443         {{ var3 }}
444     {% endif %}{% endif %}{% endif %}
449 Loop over each item in an array.  For example, to display a list of athletes
450 provided in ``athlete_list``::
452     <ul>
453     {% for athlete in athlete_list %}
454         <li>{{ athlete.name }}</li>
455     {% endfor %}
456     </ul>
458 You can loop over a list in reverse by using ``{% for obj in list reversed %}``.
460 **New in Django development version**
461 If you need to loop over a list of lists, you can unpack the values
462 in eachs sub-list into a set of known names. For example, if your context contains
463 a list of (x,y) coordinates called ``points``, you could use the following
464 to output the list of points:: 
466     {% for x, y in points %}
467         There is a point at {{ x }},{{ y }}
468     {% endfor %}
469     
470 This can also be useful if you need to access the items in a dictionary. 
471 For example, if your context contained a dictionary ``data``, the following
472 would display the keys and values of the dictionary::
474     {% for key, value in data.items %}
475         {{ key }}: {{ value }}
476     {% endfor %}
478 The for loop sets a number of variables available within the loop:
480     ==========================  ================================================
481     Variable                    Description
482     ==========================  ================================================
483     ``forloop.counter``         The current iteration of the loop (1-indexed)
484     ``forloop.counter0``        The current iteration of the loop (0-indexed)
485     ``forloop.revcounter``      The number of iterations from the end of the
486                                 loop (1-indexed)
487     ``forloop.revcounter0``     The number of iterations from the end of the
488                                 loop (0-indexed)
489     ``forloop.first``           True if this is the first time through the loop
490     ``forloop.last``            True if this is the last time through the loop
491     ``forloop.parentloop``      For nested loops, this is the loop "above" the
492                                 current one
493     ==========================  ================================================
498 The ``{% if %}`` tag evaluates a variable, and if that variable is "true" (i.e.
499 exists, is not empty, and is not a false boolean value) the contents of the
500 block are output::
502     {% if athlete_list %}
503         Number of athletes: {{ athlete_list|length }}
504     {% else %}
505         No athletes.
506     {% endif %}
508 In the above, if ``athlete_list`` is not empty, the number of athletes will be
509 displayed by the ``{{ athlete_list|length }}`` variable.
511 As you can see, the ``if`` tag can take an optional ``{% else %}`` clause that
512 will be displayed if the test fails.
514 ``if`` tags may use ``and``, ``or`` or ``not`` to test a number of variables or
515 to negate a given variable::
517     {% if athlete_list and coach_list %}
518         Both athletes and coaches are available.
519     {% endif %}
521     {% if not athlete_list %}
522         There are no athletes.
523     {% endif %}
525     {% if athlete_list or coach_list %}
526         There are some athletes or some coaches.
527     {% endif %}
529     {% if not athlete_list or coach_list %}
530         There are no athletes or there are some coaches (OK, so
531         writing English translations of boolean logic sounds
532         stupid; it's not our fault).
533     {% endif %}
535     {% if athlete_list and not coach_list %}
536         There are some athletes and absolutely no coaches.
537     {% endif %}
539 ``if`` tags don't allow ``and`` and ``or`` clauses within the same tag, because
540 the order of logic would be ambiguous. For example, this is invalid::
542     {% if athlete_list and coach_list or cheerleader_list %}
544 If you need to combine ``and`` and ``or`` to do advanced logic, just use nested
545 ``if`` tags. For example::
547     {% if athlete_list %}
548         {% if coach_list or cheerleader_list %}
549             We have athletes, and either coaches or cheerleaders!
550         {% endif %}
551     {% endif %}
553 Multiple uses of the same logical operator are fine, as long as you use the
554 same operator. For example, this is valid::
556     {% if athlete_list or coach_list or parent_list or teacher_list %}
558 ifchanged
559 ~~~~~~~~~
561 Check if a value has changed from the last iteration of a loop.
563 The 'ifchanged' block tag is used within a loop. It has two possible uses.
565 1. Checks its own rendered contents against its previous state and only
566    displays the content if it has changed. For example, this displays a list of
567    days, only displaying the month if it changes::
569         <h1>Archive for {{ year }}</h1>
571         {% for date in days %}
572             {% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %}
573             <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a>
574         {% endfor %}
576 2. If given a variable, check whether that variable has changed. For
577    example, the following shows the date every time it changes, but
578    only shows the hour if both the hour and the date has changed::
580         {% for date in days %}
581             {% ifchanged date.date %} {{ date.date }} {% endifchanged %}
582             {% ifchanged date.hour date.date %}
583                 {{ date.hour }}
584             {% endifchanged %}
585         {% endfor %}
587 ifequal
588 ~~~~~~~
590 Output the contents of the block if the two arguments equal each other.
592 Example::
594     {% ifequal user.id comment.user_id %}
595         ...
596     {% endifequal %}
598 As in the ``{% if %}`` tag, an ``{% else %}`` clause is optional.
600 The arguments can be hard-coded strings, so the following is valid::
602     {% ifequal user.username "adrian" %}
603         ...
604     {% endifequal %}
606 It is only possible to compare an argument to template variables or strings.
607 You cannot check for equality with Python objects such as ``True`` or
608 ``False``.  If you need to test if something is true or false, use the ``if``
609 tag instead.
611 ifnotequal
612 ~~~~~~~~~~
614 Just like ``ifequal``, except it tests that the two arguments are not equal.
616 include
617 ~~~~~~~
619 Loads a template and renders it with the current context. This is a way of
620 "including" other templates within a template.
622 The template name can either be a variable or a hard-coded (quoted) string,
623 in either single or double quotes.
625 This example includes the contents of the template ``"foo/bar.html"``::
627     {% include "foo/bar.html" %}
629 This example includes the contents of the template whose name is contained in
630 the variable ``template_name``::
632     {% include template_name %}
634 An included template is rendered with the context of the template that's
635 including it. This example produces the output ``"Hello, John"``:
637     * Context: variable ``person`` is set to ``"john"``.
638     * Template::
640         {% include "name_snippet.html" %}
642     * The ``name_snippet.html`` template::
644         Hello, {{ person }}
646 See also: ``{% ssi %}``.
648 load
649 ~~~~
651 Load a custom template tag set.
653 See `Custom tag and filter libraries`_ for more information.
658 Display the date, formatted according to the given string.
660 Uses the same format as PHP's ``date()`` function (http://php.net/date)
661 with some custom extensions.
663 Available format strings:
665     ================  ========================================  =====================
666     Format character  Description                               Example output
667     ================  ========================================  =====================
668     a                 ``'a.m.'`` or ``'p.m.'`` (Note that       ``'a.m.'``
669                       this is slightly different than PHP's
670                       output, because this includes periods
671                       to match Associated Press style.)
672     A                 ``'AM'`` or ``'PM'``.                     ``'AM'``
673     b                 Month, textual, 3 letters, lowercase.     ``'jan'``
674     B                 Not implemented.
675     d                 Day of the month, 2 digits with           ``'01'`` to ``'31'``
676                       leading zeros.
677     D                 Day of the week, textual, 3 letters.      ``'Fri'``
678     f                 Time, in 12-hour hours and minutes,       ``'1'``, ``'1:30'``
679                       with minutes left off if they're zero.
680                       Proprietary extension.
681     F                 Month, textual, long.                     ``'January'``
682     g                 Hour, 12-hour format without leading      ``'1'`` to ``'12'``
683                       zeros.
684     G                 Hour, 24-hour format without leading      ``'0'`` to ``'23'``
685                       zeros.
686     h                 Hour, 12-hour format.                     ``'01'`` to ``'12'``
687     H                 Hour, 24-hour format.                     ``'00'`` to ``'23'``
688     i                 Minutes.                                  ``'00'`` to ``'59'``
689     I                 Not implemented.
690     j                 Day of the month without leading          ``'1'`` to ``'31'``
691                       zeros.
692     l                 Day of the week, textual, long.           ``'Friday'``
693     L                 Boolean for whether it's a leap year.     ``True`` or ``False``
694     m                 Month, 2 digits with leading zeros.       ``'01'`` to ``'12'``
695     M                 Month, textual, 3 letters.                ``'Jan'``
696     n                 Month without leading zeros.              ``'1'`` to ``'12'``
697     N                 Month abbreviation in Associated Press    ``'Jan.'``, ``'Feb.'``, ``'March'``, ``'May'``
698                       style. Proprietary extension.
699     O                 Difference to Greenwich time in hours.    ``'+0200'``
700     P                 Time, in 12-hour hours, minutes and       ``'1 a.m.'``, ``'1:30 p.m.'``, ``'midnight'``, ``'noon'``, ``'12:30 p.m.'``
701                       'a.m.'/'p.m.', with minutes left off
702                       if they're zero and the special-case
703                       strings 'midnight' and 'noon' if
704                       appropriate. Proprietary extension.
705     r                 RFC 822 formatted date.                   ``'Thu, 21 Dec 2000 16:01:07 +0200'``
706     s                 Seconds, 2 digits with leading zeros.     ``'00'`` to ``'59'``
707     S                 English ordinal suffix for day of the     ``'st'``, ``'nd'``, ``'rd'`` or ``'th'``
708                       month, 2 characters.
709     t                 Number of days in the given month.        ``28`` to ``31``
710     T                 Time zone of this machine.                ``'EST'``, ``'MDT'``
711     U                 Not implemented.
712     w                 Day of the week, digits without           ``'0'`` (Sunday) to ``'6'`` (Saturday)
713                       leading zeros.
714     W                 ISO-8601 week number of year, with        ``1``, ``23``
715                       weeks starting on Monday.
716     y                 Year, 2 digits.                           ``'99'``
717     Y                 Year, 4 digits.                           ``'1999'``
718     z                 Day of the year.                          ``0`` to ``365``
719     Z                 Time zone offset in seconds. The          ``-43200`` to ``43200``
720                       offset for timezones west of UTC is
721                       always negative, and for those east of
722                       UTC is always positive.
723     ================  ========================================  =====================
725 Example::
727     It is {% now "jS F Y H:i" %}
729 Note that you can backslash-escape a format string if you want to use the
730 "raw" value. In this example, "f" is backslash-escaped, because otherwise
731 "f" is a format string that displays the time. The "o" doesn't need to be
732 escaped, because it's not a format character::
734     It is the {% now "jS o\f F" %}
736 This would display as "It is the 4th of September".
738 regroup
739 ~~~~~~~
741 Regroup a list of alike objects by a common attribute.
743 This complex tag is best illustrated by use of an example:  say that ``people``
744 is a list of people represented by dictionaries with ``first_name``,
745 ``last_name``, and ``gender`` keys::
747     people = [
748         {'first_name': 'George', 'last_name': 'Bush', 'gender': 'Male'},
749         {'first_name': 'Bill', 'last_name': 'Clinton', 'gender': 'Male'},
750         {'first_name': 'Margaret', 'last_name': 'Thatcher', 'gender': 'Female'},
751         {'first_name': 'Condoleezza', 'last_name': 'Rice', 'gender': 'Female'},
752         {'first_name': 'Pat', 'last_name': 'Smith', 'gender': 'Unknown'},
753     ]
755 ...and you'd like to display a hierarchical list that is ordered by gender,
756 like this:
758     * Male:
759         * George Bush
760         * Bill Clinton
761     * Female:
762         * Margaret Thatcher
763         * Condoleezza Rice
764     * Unknown:
765         * Pat Smith
767 You can use the ``{% regroup %}`` tag to group the list of people by gender.
768 The following snippet of template code would accomplish this::
770     {% regroup people by gender as gender_list %}
772     <ul>
773     {% for gender in gender_list %}
774         <li>{{ gender.grouper }}
775         <ul>
776             {% for item in gender.list %}
777             <li>{{ item.first_name }} {{ item.last_name }}</li>
778             {% endfor %}
779         </ul>
780         </li>
781     {% endfor %}
782     </ul>
784 Let's walk through this example. ``{% regroup %}`` takes three arguments: the
785 list you want to regroup, the attribute to group by, and the name of the
786 resulting list. Here, we're regrouping the ``people`` list by the ``gender``
787 attribute and calling the result ``gender_list``.
789 ``{% regroup %}`` produces a list (in this case, ``gender_list``) of
790 **group objects**. Each group object has two attributes:
792     * ``grouper`` -- the item that was grouped by (e.g., the string "Male" or
793       "Female").
794     * ``list`` -- a list of all items in this group (e.g., a list of all people
795       with gender='Male').
797 Note that ``{% regroup %}`` does not order its input! Our example relies on
798 the fact that the ``people`` list was ordered by ``gender`` in the first place.
799 If the ``people`` list did *not* order its members by ``gender``, the regrouping
800 would naively display more than one group for a single gender. For example,
801 say the ``people`` list was set to this (note that the males are not grouped
802 together)::
804     people = [
805         {'first_name': 'Bill', 'last_name': 'Clinton', 'gender': 'Male'},
806         {'first_name': 'Pat', 'last_name': 'Smith', 'gender': 'Unknown'},
807         {'first_name': 'Margaret', 'last_name': 'Thatcher', 'gender': 'Female'},
808         {'first_name': 'George', 'last_name': 'Bush', 'gender': 'Male'},
809         {'first_name': 'Condoleezza', 'last_name': 'Rice', 'gender': 'Female'},
810     ]
812 With this input for ``people``, the example ``{% regroup %}`` template code
813 above would result in the following output:
815     * Male:
816         * Bill Clinton
817     * Unknown:
818         * Pat Smith
819     * Female:
820         * Margaret Thatcher
821     * Male:
822         * George Bush
823     * Female:
824         * Condoleezza Rice
826 The easiest solution to this gotcha is to make sure in your view code that the
827 data is ordered according to how you want to display it.
829 Another solution is to sort the data in the template using the ``dictsort``
830 filter, if your data is in a list of dictionaries::
832     {% regroup people|dictsort:"gender" by gender as gender_list %}
834 spaceless
835 ~~~~~~~~~
837 Removes whitespace between HTML tags. This includes tab
838 characters and newlines.
840 Example usage::
842     {% spaceless %}
843         <p>
844             <a href="foo/">Foo</a>
845         </p>
846     {% endspaceless %}
848 This example would return this HTML::
850     <p><a href="foo/">Foo</a></p>
852 Only space between *tags* is removed -- not space between tags and text. In
853 this example, the space around ``Hello`` won't be stripped::
855     {% spaceless %}
856         <strong>
857             Hello
858         </strong>
859     {% endspaceless %}
864 Output the contents of a given file into the page.
866 Like a simple "include" tag, ``{% ssi %}`` includes the contents of another
867 file -- which must be specified using an absolute path -- in the current
868 page::
870     {% ssi /home/html/ljworld.com/includes/right_generic.html %}
872 If the optional "parsed" parameter is given, the contents of the included
873 file are evaluated as template code, within the current context::
875     {% ssi /home/html/ljworld.com/includes/right_generic.html parsed %}
877 Note that if you use ``{% ssi %}``, you'll need to define
878 `ALLOWED_INCLUDE_ROOTS`_ in your Django settings, as a security measure.
880 See also: ``{% include %}``.
882 .. _ALLOWED_INCLUDE_ROOTS: ../settings/#allowed-include-roots
884 templatetag
885 ~~~~~~~~~~~
887 Output one of the syntax characters used to compose template tags.
889 Since the template system has no concept of "escaping", to display one of the
890 bits used in template tags, you must use the ``{% templatetag %}`` tag.
892 The argument tells which template bit to output:
894     ==================  =======
895     Argument            Outputs
896     ==================  =======
897     ``openblock``       ``{%``
898     ``closeblock``      ``%}``
899     ``openvariable``    ``{{``
900     ``closevariable``   ``}}``
901     ``openbrace``       ``{``
902     ``closebrace``      ``}``
903     ``opencomment``     ``{#``
904     ``closecomment``    ``#}``
905     ==================  =======
910 **Note that the syntax for this tag may change in the future, as we make it more robust.**
912 Returns an absolute URL (i.e., a URL without the domain name) matching a given
913 view function and optional parameters. This is a way to output links without
914 violating the DRY principle by having to hard-code URLs in your templates::
916     {% url path.to.some_view arg1,arg2,name1=value1 %}
918 The first argument is a path to a view function in the format
919 ``package.package.module.function``. Additional arguments are optional and
920 should be comma-separated values that will be used as positional and keyword
921 arguments in the URL. All arguments required by the URLconf should be present.
923 For example, suppose you have a view, ``app_views.client``, whose URLconf
924 takes a client ID (here, ``client()`` is a method inside the views file
925 ``app_views.py``). The URLconf line might look like this::
927     ('^client/(\d+)/$', 'app_views.client')
929 If this app's URLconf is included into the project's URLconf under a path
930 such as this::
932     ('^clients/', include('project_name.app_name.urls'))
934 ...then, in a template, you can create a link to this view like this::
936     {% url app_views.client client.id %}
938 The template tag will output the string ``/clients/client/123/``.
940 widthratio
941 ~~~~~~~~~~
943 For creating bar charts and such, this tag calculates the ratio of a given value
944 to a maximum value, and then applies that ratio to a constant.
946 For example::
948     <img src="bar.gif" height="10" width="{% widthratio this_value max_value 100 %}" />
950 Above, if ``this_value`` is 175 and ``max_value`` is 200, the the image in the
951 above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5
952 which is rounded up to 88).
954 with
955 ~~~~
957 **New in Django development version**
959 Caches a complex variable under a simpler name. This is useful when accessing
960 an "expensive" method (e.g., one that hits the database) multiple times.
962 For example::
964     {% with business.employees.count as total %}
965         {{ total }} employee{{ total|pluralize }}
966     {% endwith %}
968 The populated variable (in the example above, ``total``) is only available
969 between the ``{% with %}`` and ``{% endwith %}`` tags.
971 Built-in filter reference
972 -------------------------
977 Adds the arg to the value.
979 addslashes
980 ~~~~~~~~~~
982 Adds slashes. Useful for passing strings to JavaScript, for example.
985 capfirst
986 ~~~~~~~~
988 Capitalizes the first character of the value.
990 center
991 ~~~~~~
993 Centers the value in a field of a given width.
998 Removes all values of arg from the given string.
1000 date
1001 ~~~~
1003 Formats a date according to the given format (same as the `now`_ tag).
1005 default
1006 ~~~~~~~
1008 If value is unavailable, use given default.
1010 default_if_none
1011 ~~~~~~~~~~~~~~~
1013 If value is ``None``, use given default.
1015 dictsort
1016 ~~~~~~~~
1018 Takes a list of dictionaries, returns that list sorted by the key given in
1019 the argument.
1021 dictsortreversed
1022 ~~~~~~~~~~~~~~~~
1024 Takes a list of dictionaries, returns that list sorted in reverse order by the
1025 key given in the argument.
1027 divisibleby
1028 ~~~~~~~~~~~
1030 Returns true if the value is divisible by the argument.
1032 escape
1033 ~~~~~~
1035 Escapes a string's HTML. Specifically, it makes these replacements:
1037     * ``"&"`` to ``"&amp;"``
1038     * ``<`` to ``"&lt;"``
1039     * ``>`` to ``"&gt;"``
1040     * ``'"'`` (double quote) to ``'&quot;'``
1041     * ``"'"`` (single quote) to ``'&#39;'``
1043 filesizeformat
1044 ~~~~~~~~~~~~~~
1046 Format the value like a 'human-readable' file size (i.e. ``'13 KB'``,
1047 ``'4.1 MB'``, ``'102 bytes'``, etc).
1049 first
1050 ~~~~~
1052 Returns the first item in a list.
1054 fix_ampersands
1055 ~~~~~~~~~~~~~~
1057 Replaces ampersands with ``&amp;`` entities.
1059 floatformat
1060 ~~~~~~~~~~~
1062 When used without an argument, rounds a floating-point number to one decimal
1063 place -- but only if there's a decimal part to be displayed. For example:
1065     * ``36.123`` gets converted to ``36.1``
1066     * ``36.15`` gets converted to ``36.2``
1067     * ``36`` gets converted to ``36``
1069 If used with a numeric integer argument, ``floatformat`` rounds a number to that
1070 many decimal places.  For example:
1072     * ``36.1234`` with floatformat:3 gets converted to ``36.123``
1073     * ``36`` with floatformat:4 gets converted to ``36.0000``
1075 If the argument passed to ``floatformat`` is negative, it will round a number to
1076 that many decimal places -- but only if there's a decimal part to be displayed.
1077 For example:
1079     * ``36.1234`` with floatformat:-3 gets converted to ``36.123``
1080     * ``36`` with floatformat:-4 gets converted to ``36``
1082 Using ``floatformat`` with no argument is equivalent to using ``floatformat`` with
1083 an argument of ``-1``.
1085 get_digit
1086 ~~~~~~~~~
1088 Given a whole number, returns the requested digit of it, where 1 is the
1089 right-most digit, 2 is the second-right-most digit, etc. Returns the original
1090 value for invalid input (if input or argument is not an integer, or if argument
1091 is less than 1). Otherwise, output is always an integer.
1093 iriencode
1094 ~~~~~~~~~
1096 Converts an IRI (Internationalized Resource Identifier) to a string that is
1097 suitable for including in a URL. This is necessary if you're trying to use
1098 strings containing non-ASCII characters in a URL.
1100 It's safe to use this filter on a string that has already gone through the
1101 ``urlencode`` filter.
1103 join
1104 ~~~~
1106 Joins a list with a string, like Python's ``str.join(list)``.
1108 length
1109 ~~~~~~
1111 Returns the length of the value. Useful for lists.
1113 length_is
1114 ~~~~~~~~~
1116 Returns a boolean of whether the value's length is the argument.
1118 linebreaks
1119 ~~~~~~~~~~
1121 Converts newlines into ``<p>`` and ``<br />`` tags.
1123 linebreaksbr
1124 ~~~~~~~~~~~~
1126 Converts newlines into ``<br />`` tags.
1128 linenumbers
1129 ~~~~~~~~~~~
1131 Displays text with line numbers.
1133 ljust
1134 ~~~~~
1136 Left-aligns the value in a field of a given width.
1138 **Argument:** field size
1140 lower
1141 ~~~~~
1143 Converts a string into all lowercase.
1145 make_list
1146 ~~~~~~~~~
1148 Returns the value turned into a list. For an integer, it's a list of
1149 digits. For a string, it's a list of characters.
1151 phone2numeric
1152 ~~~~~~~~~~~~~
1154 Converts a phone number (possibly containing letters) to its numerical
1155 equivalent. For example, ``'800-COLLECT'`` will be converted to
1156 ``'800-2655328'``.
1158 The input doesn't have to be a valid phone number. This will happily convert
1159 any string.
1161 pluralize
1162 ~~~~~~~~~
1164 Returns a plural suffix if the value is not 1. By default, this suffix is ``'s'``.
1166 Example::
1168     You have {{ num_messages }} message{{ num_messages|pluralize }}.
1170 For words that require a suffix other than ``'s'``, you can provide an alternate
1171 suffix as a parameter to the filter.
1173 Example::
1175     You have {{ num_walruses }} walrus{{ num_walrus|pluralize:"es" }}.
1177 For words that don't pluralize by simple suffix, you can specify both a
1178 singular and plural suffix, separated by a comma.
1180 Example::
1182     You have {{ num_cherries }} cherr{{ num_cherries|pluralize:"y,ies" }}.
1184 pprint
1185 ~~~~~~
1187 A wrapper around pprint.pprint -- for debugging, really.
1189 random
1190 ~~~~~~
1192 Returns a random item from the list.
1194 removetags
1195 ~~~~~~~~~~
1197 Removes a space separated list of [X]HTML tags from the output.
1199 rjust
1200 ~~~~~
1202 Right-aligns the value in a field of a given width.
1204 **Argument:** field size
1206 slice
1207 ~~~~~
1209 Returns a slice of the list.
1211 Uses the same syntax as Python's list slicing. See
1212 http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice
1213 for an introduction.
1215 Example: ``{{ some_list|slice:":2" }}``
1217 slugify
1218 ~~~~~~~
1220 Converts to lowercase, removes non-word characters (alphanumerics and
1221 underscores) and converts spaces to hyphens. Also strips leading and trailing
1222 whitespace.
1224 stringformat
1225 ~~~~~~~~~~~~
1227 Formats the variable according to the argument, a string formatting specifier.
1228 This specifier uses Python string formating syntax, with the exception that
1229 the leading "%" is dropped.
1231 See http://docs.python.org/lib/typesseq-strings.html for documentation of
1232 Python string formatting
1234 striptags
1235 ~~~~~~~~~
1237 Strips all [X]HTML tags.
1239 time
1240 ~~~~
1242 Formats a time according to the given format (same as the `now`_ tag).
1243 The time filter will only accept parameters in the format string that relate
1244 to the time of day, not the date (for obvious reasons). If you need to
1245 format a date, use the `date`_ filter.
1247 timesince
1248 ~~~~~~~~~
1250 Formats a date as the time since that date (i.e. "4 days, 6 hours").
1252 Takes an optional argument that is a variable containing the date to use as
1253 the comparison point (without the argument, the comparison point is *now*).
1254 For example, if ``blog_date`` is a date instance representing midnight on 1
1255 June 2006, and ``comment_date`` is a date instance for 08:00 on 1 June 2006,
1256 then ``{{ comment_date|timesince:blog_date }}`` would return "8 hours".
1258 timeuntil
1259 ~~~~~~~~~
1261 Similar to ``timesince``, except that it measures the time from now until the
1262 given date or datetime. For example, if today is 1 June 2006 and
1263 ``conference_date`` is a date instance holding 29 June 2006, then
1264 ``{{ conference_date|timeuntil }}`` will return "28 days".
1266 Takes an optional argument that is a variable containing the date to use as
1267 the comparison point (instead of *now*). If ``from_date`` contains 22 June
1268 2006, then ``{{ conference_date|timeuntil:from_date }}`` will return "7 days".
1270 title
1271 ~~~~~
1273 Converts a string into titlecase.
1275 truncatewords
1276 ~~~~~~~~~~~~~
1278 Truncates a string after a certain number of words.
1280 **Argument:** Number of words to truncate after
1282 truncatewords_html
1283 ~~~~~~~~~~~~~~~~~~
1285 Similar to ``truncatewords``, except that it is aware of HTML tags. Any tags
1286 that are opened in the string and not closed before the truncation point, are
1287 closed immediately after the truncation.
1289 This is less efficient than ``truncatewords``, so should only be used when it
1290 is being passed HTML text.
1292 unordered_list
1293 ~~~~~~~~~~~~~~
1295 Recursively takes a self-nested list and returns an HTML unordered list --
1296 WITHOUT opening and closing <ul> tags.
1298 The list is assumed to be in the proper format. For example, if ``var`` contains
1299 ``['States', [['Kansas', [['Lawrence', []], ['Topeka', []]]], ['Illinois', []]]]``,
1300 then ``{{ var|unordered_list }}`` would return::
1302     <li>States
1303     <ul>
1304             <li>Kansas
1305             <ul>
1306                     <li>Lawrence</li>
1307                     <li>Topeka</li>
1308             </ul>
1309             </li>
1310             <li>Illinois</li>
1311     </ul>
1312     </li>
1314 upper
1315 ~~~~~
1317 Converts a string into all uppercase.
1319 urlencode
1320 ~~~~~~~~~
1322 Escapes a value for use in a URL.
1324 urlize
1325 ~~~~~~
1327 Converts URLs in plain text into clickable links.
1329 Note that if ``urlize`` is applied to text that already contains HTML markup,
1330 things won't work as expected. Apply this filter only to *plain* text.
1332 urlizetrunc
1333 ~~~~~~~~~~~
1335 Converts URLs into clickable links, truncating URLs longer than the given
1336 character limit.
1338 As with urlize_, this filter should only be applied to *plain* text.
1340 **Argument:** Length to truncate URLs to
1342 wordcount
1343 ~~~~~~~~~
1345 Returns the number of words.
1347 wordwrap
1348 ~~~~~~~~
1350 Wraps words at specified line length.
1352 **Argument:** number of characters at which to wrap the text
1354 yesno
1355 ~~~~~
1357 Given a string mapping values for true, false and (optionally) None,
1358 returns one of those strings according to the value:
1360 ==========  ======================  ==================================
1361 Value       Argument                Outputs
1362 ==========  ======================  ==================================
1363 ``True``    ``"yeah,no,maybe"``     ``yeah``
1364 ``False``   ``"yeah,no,maybe"``     ``no``
1365 ``None``    ``"yeah,no,maybe"``     ``maybe``
1366 ``None``    ``"yeah,no"``           ``"no"`` (converts None to False
1367                                     if no mapping for None is given)
1368 ==========  ======================  ==================================
1370 Other tags and filter libraries
1371 ===============================
1373 Django comes with a couple of other template-tag libraries that you have to
1374 enable explicitly in your ``INSTALLED_APPS`` setting and enable in your
1375 template with the ``{% load %}`` tag.
1377 django.contrib.humanize
1378 -----------------------
1380 A set of Django template filters useful for adding a "human touch" to data. See
1381 the `humanize documentation`_.
1383 .. _humanize documentation: ../add_ons/#humanize
1385 django.contrib.markup
1386 ---------------------
1388 A collection of template filters that implement these common markup languages:
1390     * Textile
1391     * Markdown
1392     * ReST (ReStructured Text)
1394 django.contrib.webdesign
1395 ------------------------
1397 A collection of template tags that can be useful while designing a website,
1398 such as a generator of Lorem Ipsum text. See the `webdesign documentation`_.
1400 .. _webdesign documentation: ../webdesign/