Fixed #4764 -- Added reference to Locale middleware in middleware docs. Thanks, dan...
[django.git] / docs / templates.txt
blobf5ed1fe74b1865ace290115b700e5d401215468d
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 ``Person`` objects that have ``first_name``, ``last_name``, and
745 ``gender`` attributes, and you'd like to display a list that looks like:
747     * Male:
748         * George Bush
749         * Bill Clinton
750     * Female:
751         * Margaret Thatcher
752         * Condoleezza Rice
753     * Unknown:
754         * Pat Smith
756 The following snippet of template code would accomplish this dubious task::
758     {% regroup people by gender as grouped %}
759     <ul>
760     {% for group in grouped %}
761         <li>{{ group.grouper }}
762         <ul>
763             {% for item in group.list %}
764             <li>{{ item }}</li>
765             {% endfor %}
766         </ul>
767         </li>
768     {% endfor %}
769     </ul>
771 As you can see, ``{% regroup %}`` populates a variable with a list of objects
772 with ``grouper`` and ``list`` attributes.  ``grouper`` contains the item that
773 was grouped by; ``list`` contains the list of objects that share that
774 ``grouper``.  In this case, ``grouper`` would be ``Male``, ``Female`` and
775 ``Unknown``, and ``list`` is the list of people with those genders.
777 Note that ``{% regroup %}`` does not work when the list to be grouped is not
778 sorted by the key you are grouping by!  This means that if your list of people
779 was not sorted by gender, you'd need to make sure it is sorted before using it,
780 i.e.::
782     {% regroup people|dictsort:"gender" by gender as grouped %}
784 spaceless
785 ~~~~~~~~~
787 Removes whitespace between HTML tags. This includes tab
788 characters and newlines.
790 Example usage::
792     {% spaceless %}
793         <p>
794             <a href="foo/">Foo</a>
795         </p>
796     {% endspaceless %}
798 This example would return this HTML::
800     <p><a href="foo/">Foo</a></p>
802 Only space between *tags* is removed -- not space between tags and text. In
803 this example, the space around ``Hello`` won't be stripped::
805     {% spaceless %}
806         <strong>
807             Hello
808         </strong>
809     {% endspaceless %}
814 Output the contents of a given file into the page.
816 Like a simple "include" tag, ``{% ssi %}`` includes the contents of another
817 file -- which must be specified using an absolute path -- in the current
818 page::
820     {% ssi /home/html/ljworld.com/includes/right_generic.html %}
822 If the optional "parsed" parameter is given, the contents of the included
823 file are evaluated as template code, within the current context::
825     {% ssi /home/html/ljworld.com/includes/right_generic.html parsed %}
827 Note that if you use ``{% ssi %}``, you'll need to define
828 `ALLOWED_INCLUDE_ROOTS`_ in your Django settings, as a security measure.
830 See also: ``{% include %}``.
832 .. _ALLOWED_INCLUDE_ROOTS: ../settings/#allowed-include-roots
834 templatetag
835 ~~~~~~~~~~~
837 Output one of the syntax characters used to compose template tags.
839 Since the template system has no concept of "escaping", to display one of the
840 bits used in template tags, you must use the ``{% templatetag %}`` tag.
842 The argument tells which template bit to output:
844     ==================  =======
845     Argument            Outputs
846     ==================  =======
847     ``openblock``       ``{%``
848     ``closeblock``      ``%}``
849     ``openvariable``    ``{{``
850     ``closevariable``   ``}}``
851     ``openbrace``       ``{``
852     ``closebrace``      ``}``
853     ``opencomment``     ``{#``
854     ``closecomment``    ``#}``
855     ==================  =======
860 **Note that the syntax for this tag may change in the future, as we make it more robust.**
862 Returns an absolute URL (i.e., a URL without the domain name) matching a given
863 view function and optional parameters. This is a way to output links without
864 violating the DRY principle by having to hard-code URLs in your templates::
866     {% url path.to.some_view arg1,arg2,name1=value1 %}
868 The first argument is a path to a view function in the format
869 ``package.package.module.function``. Additional arguments are optional and
870 should be comma-separated values that will be used as positional and keyword
871 arguments in the URL. All arguments required by the URLconf should be present.
873 For example, suppose you have a view, ``app_views.client``, whose URLconf
874 takes a client ID (here, ``client()`` is a method inside the views file
875 ``app_views.py``). The URLconf line might look like this::
877     ('^client/(\d+)/$', 'app_views.client')
879 If this app's URLconf is included into the project's URLconf under a path
880 such as this::
882     ('^clients/', include('project_name.app_name.urls'))
884 ...then, in a template, you can create a link to this view like this::
886     {% url app_views.client client.id %}
888 The template tag will output the string ``/clients/client/123/``.
890 widthratio
891 ~~~~~~~~~~
893 For creating bar charts and such, this tag calculates the ratio of a given value
894 to a maximum value, and then applies that ratio to a constant.
896 For example::
898     <img src="bar.gif" height="10" width="{% widthratio this_value max_value 100 %}" />
900 Above, if ``this_value`` is 175 and ``max_value`` is 200, the the image in the
901 above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5
902 which is rounded up to 88).
904 with
905 ~~~~
907 **New in Django development version**
909 Caches a complex variable under a simpler name. This is useful when accessing
910 an "expensive" method (e.g., one that hits the database) multiple times.
912 For example::
914     {% with business.employees.count as total %}
915         {{ total }} employee{{ total|pluralize }}
916     {% endwith %}
918 The populated variable (in the example above, ``total``) is only available
919 between the ``{% with %}`` and ``{% endwith %}`` tags.
921 Built-in filter reference
922 -------------------------
927 Adds the arg to the value.
929 addslashes
930 ~~~~~~~~~~
932 Adds slashes. Useful for passing strings to JavaScript, for example.
935 capfirst
936 ~~~~~~~~
938 Capitalizes the first character of the value.
940 center
941 ~~~~~~
943 Centers the value in a field of a given width.
948 Removes all values of arg from the given string.
950 date
951 ~~~~
953 Formats a date according to the given format (same as the ``now`` tag).
955 default
956 ~~~~~~~
958 If value is unavailable, use given default.
960 default_if_none
961 ~~~~~~~~~~~~~~~
963 If value is ``None``, use given default.
965 dictsort
966 ~~~~~~~~
968 Takes a list of dicts, returns that list sorted by the property given in the
969 argument.
971 dictsortreversed
972 ~~~~~~~~~~~~~~~~
974 Takes a list of dicts, returns that list sorted in reverse order by the
975 property given in the argument.
977 divisibleby
978 ~~~~~~~~~~~
980 Returns true if the value is divisible by the argument.
982 escape
983 ~~~~~~
985 Escapes a string's HTML. Specifically, it makes these replacements:
987     * ``"&"`` to ``"&amp;"``
988     * ``<`` to ``"&lt;"``
989     * ``>`` to ``"&gt;"``
990     * ``'"'`` (double quote) to ``'&quot;'``
991     * ``"'"`` (single quote) to ``'&#39;'``
993 filesizeformat
994 ~~~~~~~~~~~~~~
996 Format the value like a 'human-readable' file size (i.e. ``'13 KB'``,
997 ``'4.1 MB'``, ``'102 bytes'``, etc).
999 first
1000 ~~~~~
1002 Returns the first item in a list.
1004 fix_ampersands
1005 ~~~~~~~~~~~~~~
1007 Replaces ampersands with ``&amp;`` entities.
1009 floatformat
1010 ~~~~~~~~~~~
1012 When used without an argument, rounds a floating-point number to one decimal
1013 place -- but only if there's a decimal part to be displayed. For example:
1015     * ``36.123`` gets converted to ``36.1``
1016     * ``36.15`` gets converted to ``36.2``
1017     * ``36`` gets converted to ``36``
1019 If used with a numeric integer argument, ``floatformat`` rounds a number to that
1020 many decimal places.  For example:
1022     * ``36.1234`` with floatformat:3 gets converted to ``36.123``
1023     * ``36`` with floatformat:4 gets converted to ``36.0000``
1025 If the argument passed to ``floatformat`` is negative, it will round a number to
1026 that many decimal places -- but only if there's a decimal part to be displayed.
1027 For example:
1029     * ``36.1234`` with floatformat:-3 gets converted to ``36.123``
1030     * ``36`` with floatformat:-4 gets converted to ``36``
1032 Using ``floatformat`` with no argument is equivalent to using ``floatformat`` with
1033 an argument of ``-1``.
1035 get_digit
1036 ~~~~~~~~~
1038 Given a whole number, returns the requested digit of it, where 1 is the
1039 right-most digit, 2 is the second-right-most digit, etc. Returns the original
1040 value for invalid input (if input or argument is not an integer, or if argument
1041 is less than 1). Otherwise, output is always an integer.
1043 iriencode
1044 ~~~~~~~~~
1046 Converts an IRI (Internationalized Resource Identifier) to a string that is
1047 suitable for including in a URL. This is necessary if you're trying to use
1048 strings containing non-ASCII characters in a URL.
1050 It's safe to use this filter on a string that has already gone through the
1051 ``urlencode`` filter.
1053 join
1054 ~~~~
1056 Joins a list with a string, like Python's ``str.join(list)``.
1058 length
1059 ~~~~~~
1061 Returns the length of the value. Useful for lists.
1063 length_is
1064 ~~~~~~~~~
1066 Returns a boolean of whether the value's length is the argument.
1068 linebreaks
1069 ~~~~~~~~~~
1071 Converts newlines into ``<p>`` and ``<br />`` tags.
1073 linebreaksbr
1074 ~~~~~~~~~~~~
1076 Converts newlines into ``<br />`` tags.
1078 linenumbers
1079 ~~~~~~~~~~~
1081 Displays text with line numbers.
1083 ljust
1084 ~~~~~
1086 Left-aligns the value in a field of a given width.
1088 **Argument:** field size
1090 lower
1091 ~~~~~
1093 Converts a string into all lowercase.
1095 make_list
1096 ~~~~~~~~~
1098 Returns the value turned into a list. For an integer, it's a list of
1099 digits. For a string, it's a list of characters.
1101 phone2numeric
1102 ~~~~~~~~~~~~~
1104 Converts a phone number (possibly containing letters) to its numerical
1105 equivalent. For example, ``'800-COLLECT'`` will be converted to
1106 ``'800-2655328'``.
1108 The input doesn't have to be a valid phone number. This will happily convert
1109 any string.
1111 pluralize
1112 ~~~~~~~~~
1114 Returns a plural suffix if the value is not 1. By default, this suffix is ``'s'``.
1116 Example::
1118     You have {{ num_messages }} message{{ num_messages|pluralize }}.
1120 For words that require a suffix other than ``'s'``, you can provide an alternate
1121 suffix as a parameter to the filter.
1123 Example::
1125     You have {{ num_walruses }} walrus{{ num_walrus|pluralize:"es" }}.
1127 For words that don't pluralize by simple suffix, you can specify both a
1128 singular and plural suffix, separated by a comma.
1130 Example::
1132     You have {{ num_cherries }} cherr{{ num_cherries|pluralize:"y,ies" }}.
1134 pprint
1135 ~~~~~~
1137 A wrapper around pprint.pprint -- for debugging, really.
1139 random
1140 ~~~~~~
1142 Returns a random item from the list.
1144 removetags
1145 ~~~~~~~~~~
1147 Removes a space separated list of [X]HTML tags from the output.
1149 rjust
1150 ~~~~~
1152 Right-aligns the value in a field of a given width.
1154 **Argument:** field size
1156 slice
1157 ~~~~~
1159 Returns a slice of the list.
1161 Uses the same syntax as Python's list slicing. See
1162 http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice
1163 for an introduction.
1165 Example: ``{{ some_list|slice:":2" }}``
1167 slugify
1168 ~~~~~~~
1170 Converts to lowercase, removes non-word characters (alphanumerics and
1171 underscores) and converts spaces to hyphens. Also strips leading and trailing
1172 whitespace.
1174 stringformat
1175 ~~~~~~~~~~~~
1177 Formats the variable according to the argument, a string formatting specifier.
1178 This specifier uses Python string formating syntax, with the exception that
1179 the leading "%" is dropped.
1181 See http://docs.python.org/lib/typesseq-strings.html for documentation of
1182 Python string formatting
1184 striptags
1185 ~~~~~~~~~
1187 Strips all [X]HTML tags.
1189 time
1190 ~~~~
1192 Formats a time according to the given format (same as the ``now`` tag).
1194 timesince
1195 ~~~~~~~~~
1197 Formats a date as the time since that date (i.e. "4 days, 6 hours").
1199 Takes an optional argument that is a variable containing the date to use as
1200 the comparison point (without the argument, the comparison point is *now*).
1201 For example, if ``blog_date`` is a date instance representing midnight on 1
1202 June 2006, and ``comment_date`` is a date instance for 08:00 on 1 June 2006,
1203 then ``{{ comment_date|timesince:blog_date }}`` would return "8 hours".
1205 timeuntil
1206 ~~~~~~~~~
1208 Similar to ``timesince``, except that it measures the time from now until the
1209 given date or datetime. For example, if today is 1 June 2006 and
1210 ``conference_date`` is a date instance holding 29 June 2006, then
1211 ``{{ conference_date|timeuntil }}`` will return "28 days".
1213 Takes an optional argument that is a variable containing the date to use as
1214 the comparison point (instead of *now*). If ``from_date`` contains 22 June
1215 2006, then ``{{ conference_date|timeuntil:from_date }}`` will return "7 days".
1217 title
1218 ~~~~~
1220 Converts a string into titlecase.
1222 truncatewords
1223 ~~~~~~~~~~~~~
1225 Truncates a string after a certain number of words.
1227 **Argument:** Number of words to truncate after
1229 truncatewords_html
1230 ~~~~~~~~~~~~~~~~~~
1232 Similar to ``truncatewords``, except that it is aware of HTML tags. Any tags
1233 that are opened in the string and not closed before the truncation point, are
1234 closed immediately after the truncation.
1236 This is less efficient than ``truncatewords``, so should only be used when it
1237 is being passed HTML text.
1239 unordered_list
1240 ~~~~~~~~~~~~~~
1242 Recursively takes a self-nested list and returns an HTML unordered list --
1243 WITHOUT opening and closing <ul> tags.
1245 The list is assumed to be in the proper format. For example, if ``var`` contains
1246 ``['States', [['Kansas', [['Lawrence', []], ['Topeka', []]]], ['Illinois', []]]]``,
1247 then ``{{ var|unordered_list }}`` would return::
1249     <li>States
1250     <ul>
1251             <li>Kansas
1252             <ul>
1253                     <li>Lawrence</li>
1254                     <li>Topeka</li>
1255             </ul>
1256             </li>
1257             <li>Illinois</li>
1258     </ul>
1259     </li>
1261 upper
1262 ~~~~~
1264 Converts a string into all uppercase.
1266 urlencode
1267 ~~~~~~~~~
1269 Escapes a value for use in a URL.
1271 urlize
1272 ~~~~~~
1274 Converts URLs in plain text into clickable links.
1276 urlizetrunc
1277 ~~~~~~~~~~~
1279 Converts URLs into clickable links, truncating URLs longer than the given
1280 character limit.
1282 **Argument:** Length to truncate URLs to
1284 wordcount
1285 ~~~~~~~~~
1287 Returns the number of words.
1289 wordwrap
1290 ~~~~~~~~
1292 Wraps words at specified line length.
1294 **Argument:** number of characters at which to wrap the text
1296 yesno
1297 ~~~~~
1299 Given a string mapping values for true, false and (optionally) None,
1300 returns one of those strings according to the value:
1302 ==========  ======================  ==================================
1303 Value       Argument                Outputs
1304 ==========  ======================  ==================================
1305 ``True``    ``"yeah,no,maybe"``     ``yeah``
1306 ``False``   ``"yeah,no,maybe"``     ``no``
1307 ``None``    ``"yeah,no,maybe"``     ``maybe``
1308 ``None``    ``"yeah,no"``           ``"no"`` (converts None to False
1309                                     if no mapping for None is given)
1310 ==========  ======================  ==================================
1312 Other tags and filter libraries
1313 ===============================
1315 Django comes with a couple of other template-tag libraries that you have to
1316 enable explicitly in your ``INSTALLED_APPS`` setting and enable in your
1317 template with the ``{% load %}`` tag.
1319 django.contrib.humanize
1320 -----------------------
1322 A set of Django template filters useful for adding a "human touch" to data. See
1323 the `humanize documentation`_.
1325 .. _humanize documentation: ../add_ons/#humanize
1327 django.contrib.markup
1328 ---------------------
1330 A collection of template filters that implement these common markup languages:
1332     * Textile
1333     * Markdown
1334     * ReST (ReStructured Text)
1336 django.contrib.webdesign
1337 ------------------------
1339 A collection of template tags that can be useful while designing a website,
1340 such as a generator of Lorem Ipsum text. See the `webdesign documentation`_.
1342 .. _webdesign documentation: ../webdesign/