App Engine Python SDK version 1.9.12
[gae.git] / python / lib / django-0.96 / docs / templates.txt
blobdb748ae432db3669039d7ae965ecda868b572dae
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
96 ``bio`` variable. Filter arguments always are in double quotes.
98 The `Built-in filter reference`_ below describes all the built-in filters.
100 Tags
101 ====
103 Tags look like this: ``{% tag %}``. Tags are more complex than variables: Some
104 create text in the output, some control flow by performing loops or logic, and
105 some load external information into the template to be used by later variables.
107 Some tags require beginning and ending tags (i.e.
108 ``{% tag %} ... tag contents ... {% endtag %}``). The `Built-in tag reference`_
109 below describes all the built-in tags. You can create your own tags, if you
110 know how to write Python code.
112 Comments
113 ========
115 To comment-out part of a template, use the comment syntax: ``{# #}``.
117 For example, this template would render as ``'hello'``::
119     {# greeting #}hello
121 A comment can contain any template code, invalid or not. For example::
123     {# {% if foo %}bar{% else %} #}
125 Template inheritance
126 ====================
128 The most powerful -- and thus the most complex -- part of Django's template
129 engine is template inheritance. Template inheritance allows you to build a base
130 "skeleton" template that contains all the common elements of your site and
131 defines **blocks** that child templates can override.
133 It's easiest to understand template inheritance by starting with an example::
135     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
136         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
137     <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
138     <head>
139         <link rel="stylesheet" href="style.css" />
140         <title>{% block title %}My amazing site{% endblock %}</title>
141     </head>
143     <body>
144         <div id="sidebar">
145             {% block sidebar %}
146             <ul>
147                 <li><a href="/">Home</a></li>
148                 <li><a href="/blog/">Blog</a></li>
149             </ul>
150             {% endblock %}
151         </div>
153         <div id="content">
154             {% block content %}{% endblock %}
155         </div>
156     </body>
157     </html>
159 This template, which we'll call ``base.html``, defines a simple HTML skeleton
160 document that you might use for a simple two-column page. It's the job of
161 "child" templates to fill the empty blocks with content.
163 In this example, the ``{% block %}`` tag defines three blocks that child
164 templates can fill in. All the ``block`` tag does is to tell the template
165 engine that a child template may override those portions of the template.
167 A child template might look like this::
169     {% extends "base.html" %}
171     {% block title %}My amazing blog{% endblock %}
173     {% block content %}
174     {% for entry in blog_entries %}
175         <h2>{{ entry.title }}</h2>
176         <p>{{ entry.body }}</p>
177     {% endfor %}
178     {% endblock %}
180 The ``{% extends %}`` tag is the key here. It tells the template engine that
181 this template "extends" another template. When the template system evaluates
182 this template, first it locates the parent -- in this case, "base.html".
184 At that point, the template engine will notice the three ``{% block %}`` tags
185 in ``base.html`` and replace those blocks with the contents of the child
186 template. Depending on the value of ``blog_entries``, the output might look
187 like::
189     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
190         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
191     <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
192     <head>
193         <link rel="stylesheet" href="style.css" />
194         <title>My amazing blog</title>
195     </head>
197     <body>
198         <div id="sidebar">
199             <ul>
200                 <li><a href="/">Home</a></li>
201                 <li><a href="/blog/">Blog</a></li>
202             </ul>
203         </div>
205         <div id="content">
206             <h2>Entry one</h2>
207             <p>This is my first entry.</p>
209             <h2>Entry two</h2>
210             <p>This is my second entry.</p>
211         </div>
212     </body>
213     </html>
215 Note that since the child template didn't define the ``sidebar`` block, the
216 value from the parent template is used instead. Content within a ``{% block %}``
217 tag in a parent template is always used as a fallback.
219 You can use as many levels of inheritance as needed. One common way of using
220 inheritance is the following three-level approach:
222     * Create a ``base.html`` template that holds the main look-and-feel of your
223       site.
224     * Create a ``base_SECTIONNAME.html`` template for each "section" of your
225       site. For example, ``base_news.html``, ``base_sports.html``. These
226       templates all extend ``base.html`` and include section-specific
227       styles/design.
228     * Create individual templates for each type of page, such as a news
229       article or blog entry. These templates extend the appropriate section
230       template.
232 This approach maximizes code reuse and makes it easy to add items to shared
233 content areas, such as section-wide navigation.
235 Here are some tips for working with inheritance:
237     * If you use ``{% extends %}`` in a template, it must be the first template
238       tag in that template. Template inheritance won't work, otherwise.
240     * More ``{% block %}`` tags in your base templates are better. Remember,
241       child templates don't have to define all parent blocks, so you can fill
242       in reasonable defaults in a number of blocks, then only define the ones
243       you need later. It's better to have more hooks than fewer hooks.
245     * If you find yourself duplicating content in a number of templates, it
246       probably means you should move that content to a ``{% block %}`` in a
247       parent template.
249     * If you need to get the content of the block from the parent template,
250       the ``{{ block.super }}`` variable will do the trick. This is useful
251       if you want to add to the contents of a parent block instead of
252       completely overriding it.
254     * For extra readability, you can optionally give a *name* to your
255       ``{% endblock %}`` tag. For example::
257           {% block content %}
258           ...
259           {% endblock content %}
261       In larger templates, this technique helps you see which ``{% block %}``
262       tags are being closed.
264 Finally, note that you can't define multiple ``{% block %}`` tags with the same
265 name in the same template. This limitation exists because a block tag works in
266 "both" directions. That is, a block tag doesn't just provide a hole to fill --
267 it also defines the content that fills the hole in the *parent*. If there were
268 two similarly-named ``{% block %}`` tags in a template, that template's parent
269 wouldn't know which one of the blocks' content to use.
271 Using the built-in reference
272 ============================
274 Django's admin interface includes a complete reference of all template tags and
275 filters available for a given site. To see it, go to your admin interface and
276 click the "Documentation" link in the upper right of the page.
278 The reference is divided into 4 sections: tags, filters, models, and views.
280 The **tags** and **filters** sections describe all the built-in tags (in fact,
281 the tag and filter references below come directly from those pages) as well as
282 any custom tag or filter libraries available.
284 The **views** page is the most valuable. Each URL in your site has a separate
285 entry here, and clicking on a URL will show you:
287     * The name of the view function that generates that view.
288     * A short description of what the view does.
289     * The **context**, or a list of variables available in the view's template.
290     * The name of the template or templates that are used for that view.
292 Each view documentation page also has a bookmarklet that you can use to jump
293 from any page to the documentation page for that view.
295 Because Django-powered sites usually use database objects, the **models**
296 section of the documentation page describes each type of object in the system
297 along with all the fields available on that object.
299 Taken together, the documentation pages should tell you every tag, filter,
300 variable and object available to you in a given template.
302 Custom tag and filter libraries
303 ===============================
305 Certain applications provide custom tag and filter libraries. To access them in
306 a template, use the ``{% load %}`` tag::
308     {% load comments %}
310     {% comment_form for blogs.entries entry.id with is_public yes %}
312 In the above, the ``load`` tag loads the ``comments`` tag library, which then
313 makes the ``comment_form`` tag available for use. Consult the documentation
314 area in your admin to find the list of custom libraries in your installation.
316 The ``{% load %}`` tag can take multiple library names, separated by spaces.
317 Example::
319     {% load comments i18n %}
321 Custom libraries and template inheritance
322 -----------------------------------------
324 When you load a custom tag or filter library, the tags/filters are only made
325 available to the current template -- not any parent or child templates along
326 the template-inheritance path.
328 For example, if a template ``foo.html`` has ``{% load comments %}``, a child
329 template (e.g., one that has ``{% extends "foo.html" %}``) will *not* have
330 access to the comments template tags and filters. The child template is
331 responsible for its own ``{% load comments %}``.
333 This is a feature for the sake of maintainability and sanity.
335 Built-in tag and filter reference
336 =================================
338 For those without an admin site available, reference for the stock tags and
339 filters follows. Because Django is highly customizable, the reference in your
340 admin should be considered the final word on what tags and filters are
341 available, and what they do.
343 Built-in tag reference
344 ----------------------
346 block
347 ~~~~~
349 Define a block that can be overridden by child templates. See
350 `Template inheritance`_ for more information.
352 comment
353 ~~~~~~~
355 Ignore everything between ``{% comment %}`` and ``{% endcomment %}``
357 cycle
358 ~~~~~
360 Cycle among the given strings each time this tag is encountered.
362 Within a loop, cycles among the given strings each time through the loop::
364     {% for o in some_list %}
365         <tr class="{% cycle row1,row2 %}">
366             ...
367         </tr>
368     {% endfor %}
370 Outside of a loop, give the values a unique name the first time you call it,
371 then use that name each successive time through::
373         <tr class="{% cycle row1,row2,row3 as rowcolors %}">...</tr>
374         <tr class="{% cycle rowcolors %}">...</tr>
375         <tr class="{% cycle rowcolors %}">...</tr>
377 You can use any number of values, separated by commas. Make sure not to put
378 spaces between the values -- only commas.
380 debug
381 ~~~~~
383 Output a whole load of debugging information, including the current context and
384 imported modules.
386 extends
387 ~~~~~~~
389 Signal that this template extends a parent template.
391 This tag can be used in two ways:
393    * ``{% extends "base.html" %}`` (with quotes) uses the literal value
394      ``"base.html"`` as the name of the parent template to extend.
396    * ``{% extends variable %}`` uses the value of ``variable``. If the variable
397      evaluates to a string, Django will use that string as the name of the
398      parent template. If the variable evaluates to a ``Template`` object,
399      Django will use that object as the parent template.
401 See `Template inheritance`_ for more information.
403 filter
404 ~~~~~~
406 Filter the contents of the variable through variable filters.
408 Filters can also be piped through each other, and they can have arguments --
409 just like in variable syntax.
411 Sample usage::
413     {% filter escape|lower %}
414         This text will be HTML-escaped, and will appear in all lowercase.
415     {% endfilter %}
417 firstof
418 ~~~~~~~
420 Outputs the first variable passed that is not False.  Outputs nothing if all the
421 passed variables are False.
423 Sample usage::
425     {% firstof var1 var2 var3 %}
427 This is equivalent to::
429     {% if var1 %}
430         {{ var1 }}
431     {% else %}{% if var2 %}
432         {{ var2 }}
433     {% else %}{% if var3 %}
434         {{ var3 }}
435     {% endif %}{% endif %}{% endif %}
440 Loop over each item in an array.  For example, to display a list of athletes
441 given ``athlete_list``::
443     <ul>
444     {% for athlete in athlete_list %}
445         <li>{{ athlete.name }}</li>
446     {% endfor %}
447     </ul>
449 You can also loop over a list in reverse by using ``{% for obj in list reversed %}``.
451 The for loop sets a number of variables available within the loop:
453     ==========================  ================================================
454     Variable                    Description
455     ==========================  ================================================
456     ``forloop.counter``         The current iteration of the loop (1-indexed)
457     ``forloop.counter0``        The current iteration of the loop (0-indexed)
458     ``forloop.revcounter``      The number of iterations from the end of the
459                                 loop (1-indexed)
460     ``forloop.revcounter0``     The number of iterations from the end of the
461                                 loop (0-indexed)
462     ``forloop.first``           True if this is the first time through the loop
463     ``forloop.last``            True if this is the last time through the loop
464     ``forloop.parentloop``      For nested loops, this is the loop "above" the
465                                 current one
466     ==========================  ================================================
471 The ``{% if %}`` tag evaluates a variable, and if that variable is "true" (i.e.
472 exists, is not empty, and is not a false boolean value) the contents of the
473 block are output::
475     {% if athlete_list %}
476         Number of athletes: {{ athlete_list|length }}
477     {% else %}
478         No athletes.
479     {% endif %}
481 In the above, if ``athlete_list`` is not empty, the number of athletes will be
482 displayed by the ``{{ athlete_list|length }}`` variable.
484 As you can see, the ``if`` tag can take an optional ``{% else %}`` clause that
485 will be displayed if the test fails.
487 ``if`` tags may use ``and``, ``or`` or ``not`` to test a number of variables or
488 to negate a given variable::
490     {% if athlete_list and coach_list %}
491         Both athletes and coaches are available.
492     {% endif %}
494     {% if not athlete_list %}
495         There are no athletes.
496     {% endif %}
498     {% if athlete_list or coach_list %}
499         There are some athletes or some coaches.
500     {% endif %}
502     {% if not athlete_list or coach_list %}
503         There are no athletes or there are some coaches (OK, so
504         writing English translations of boolean logic sounds
505         stupid; it's not our fault).
506     {% endif %}
508     {% if athlete_list and not coach_list %}
509         There are some athletes and absolutely no coaches.
510     {% endif %}
512 ``if`` tags don't allow ``and`` and ``or`` clauses within the same tag, because
513 the order of logic would be ambiguous. For example, this is invalid::
515     {% if athlete_list and coach_list or cheerleader_list %}
517 If you need to combine ``and`` and ``or`` to do advanced logic, just use nested
518 ``if`` tags. For example::
520     {% if athlete_list %}
521         {% if coach_list or cheerleader_list %}
522             We have athletes, and either coaches or cheerleaders!
523         {% endif %}
524     {% endif %}
526 Multiple uses of the same logical operator are fine, as long as you use the
527 same operator. For example, this is valid::
529     {% if athlete_list or coach_list or parent_list or teacher_list %}
531 ifchanged
532 ~~~~~~~~~
534 Check if a value has changed from the last iteration of a loop.
536 The 'ifchanged' block tag is used within a loop. It has two possible uses.
538 1. Checks its own rendered contents against its previous state and only
539    displays the content if it has changed. For example, this displays a list of
540    days, only displaying the month if it changes::
542         <h1>Archive for {{ year }}</h1>
544         {% for date in days %}
545             {% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %}
546             <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a>
547         {% endfor %}
549 2. If given a variable, check whether that variable has changed. For
550    example, the following shows the date every time it changes, but
551    only shows the hour if both the hour and the date has changed::
553         {% for date in days %}
554             {% ifchanged date.date %} {{ date.date }} {% endifchanged %}
555             {% ifchanged date.hour date.date %}
556                 {{ date.hour }}
557             {% endifchanged %}
558         {% endfor %}
560 ifequal
561 ~~~~~~~
563 Output the contents of the block if the two arguments equal each other.
565 Example::
567     {% ifequal user.id comment.user_id %}
568         ...
569     {% endifequal %}
571 As in the ``{% if %}`` tag, an ``{% else %}`` clause is optional.
573 The arguments can be hard-coded strings, so the following is valid::
575     {% ifequal user.username "adrian" %}
576         ...
577     {% endifequal %}
579 It is only possible to compare an argument to template variables or strings.
580 You cannot check for equality with Python objects such as ``True`` or
581 ``False``.  If you need to test if something is true or false, use the ``if``
582 tag instead.
584 ifnotequal
585 ~~~~~~~~~~
587 Just like ``ifequal``, except it tests that the two arguments are not equal.
589 include
590 ~~~~~~~
592 Loads a template and renders it with the current context. This is a way of
593 "including" other templates within a template.
595 The template name can either be a variable or a hard-coded (quoted) string,
596 in either single or double quotes.
598 This example includes the contents of the template ``"foo/bar.html"``::
600     {% include "foo/bar.html" %}
602 This example includes the contents of the template whose name is contained in
603 the variable ``template_name``::
605     {% include template_name %}
607 An included template is rendered with the context of the template that's
608 including it. This example produces the output ``"Hello, John"``:
610     * Context: variable ``person`` is set to ``"john"``.
611     * Template::
613         {% include "name_snippet.html" %}
615     * The ``name_snippet.html`` template::
617         Hello, {{ person }}
619 See also: ``{% ssi %}``.
621 load
622 ~~~~
624 Load a custom template tag set.
626 See `Custom tag and filter libraries`_ for more information.
631 Display the date, formatted according to the given string.
633 Uses the same format as PHP's ``date()`` function (http://php.net/date)
634 with some custom extensions.
636 Available format strings:
638     ================  ========================================  =====================
639     Format character  Description                               Example output
640     ================  ========================================  =====================
641     a                 ``'a.m.'`` or ``'p.m.'`` (Note that       ``'a.m.'``
642                       this is slightly different than PHP's
643                       output, because this includes periods
644                       to match Associated Press style.)
645     A                 ``'AM'`` or ``'PM'``.                     ``'AM'``
646     b                 Month, textual, 3 letters, lowercase.     ``'jan'``
647     B                 Not implemented.
648     d                 Day of the month, 2 digits with           ``'01'`` to ``'31'``
649                       leading zeros.
650     D                 Day of the week, textual, 3 letters.      ``'Fri'``
651     f                 Time, in 12-hour hours and minutes,       ``'1'``, ``'1:30'``
652                       with minutes left off if they're zero.
653                       Proprietary extension.
654     F                 Month, textual, long.                     ``'January'``
655     g                 Hour, 12-hour format without leading      ``'1'`` to ``'12'``
656                       zeros.
657     G                 Hour, 24-hour format without leading      ``'0'`` to ``'23'``
658                       zeros.
659     h                 Hour, 12-hour format.                     ``'01'`` to ``'12'``
660     H                 Hour, 24-hour format.                     ``'00'`` to ``'23'``
661     i                 Minutes.                                  ``'00'`` to ``'59'``
662     I                 Not implemented.
663     j                 Day of the month without leading          ``'1'`` to ``'31'``
664                       zeros.
665     l                 Day of the week, textual, long.           ``'Friday'``
666     L                 Boolean for whether it's a leap year.     ``True`` or ``False``
667     m                 Month, 2 digits with leading zeros.       ``'01'`` to ``'12'``
668     M                 Month, textual, 3 letters.                ``'Jan'``
669     n                 Month without leading zeros.              ``'1'`` to ``'12'``
670     N                 Month abbreviation in Associated Press    ``'Jan.'``, ``'Feb.'``, ``'March'``, ``'May'``
671                       style. Proprietary extension.
672     O                 Difference to Greenwich time in hours.    ``'+0200'``
673     P                 Time, in 12-hour hours, minutes and       ``'1 a.m.'``, ``'1:30 p.m.'``, ``'midnight'``, ``'noon'``, ``'12:30 p.m.'``
674                       'a.m.'/'p.m.', with minutes left off
675                       if they're zero and the special-case
676                       strings 'midnight' and 'noon' if
677                       appropriate. Proprietary extension.
678     r                 RFC 822 formatted date.                   ``'Thu, 21 Dec 2000 16:01:07 +0200'``
679     s                 Seconds, 2 digits with leading zeros.     ``'00'`` to ``'59'``
680     S                 English ordinal suffix for day of the     ``'st'``, ``'nd'``, ``'rd'`` or ``'th'``
681                       month, 2 characters.
682     t                 Number of days in the given month.        ``28`` to ``31``
683     T                 Time zone of this machine.                ``'EST'``, ``'MDT'``
684     U                 Not implemented.
685     w                 Day of the week, digits without           ``'0'`` (Sunday) to ``'6'`` (Saturday)
686                       leading zeros.
687     W                 ISO-8601 week number of year, with        ``1``, ``23``
688                       weeks starting on Monday.
689     y                 Year, 2 digits.                           ``'99'``
690     Y                 Year, 4 digits.                           ``'1999'``
691     z                 Day of the year.                          ``0`` to ``365``
692     Z                 Time zone offset in seconds. The          ``-43200`` to ``43200``
693                       offset for timezones west of UTC is
694                       always negative, and for those east of
695                       UTC is always positive.
696     ================  ========================================  =====================
698 Example::
700     It is {% now "jS F Y H:i" %}
702 Note that you can backslash-escape a format string if you want to use the
703 "raw" value. In this example, "f" is backslash-escaped, because otherwise
704 "f" is a format string that displays the time. The "o" doesn't need to be
705 escaped, because it's not a format character.::
707     It is the {% now "jS o\f F" %}
709 (Displays "It is the 4th of September" %}
711 regroup
712 ~~~~~~~
714 Regroup a list of alike objects by a common attribute.
716 This complex tag is best illustrated by use of an example:  say that ``people``
717 is a list of ``Person`` objects that have ``first_name``, ``last_name``, and
718 ``gender`` attributes, and you'd like to display a list that looks like:
720     * Male:
721         * George Bush
722         * Bill Clinton
723     * Female:
724         * Margaret Thatcher
725         * Condoleezza Rice
726     * Unknown:
727         * Pat Smith
729 The following snippet of template code would accomplish this dubious task::
731     {% regroup people by gender as grouped %}
732     <ul>
733     {% for group in grouped %}
734         <li>{{ group.grouper }}
735         <ul>
736             {% for item in group.list %}
737             <li>{{ item }}</li>
738             {% endfor %}
739         </ul>
740     {% endfor %}
741     </ul>
743 As you can see, ``{% regroup %}`` populates a variable with a list of objects
744 with ``grouper`` and ``list`` attributes.  ``grouper`` contains the item that
745 was grouped by; ``list`` contains the list of objects that share that
746 ``grouper``.  In this case, ``grouper`` would be ``Male``, ``Female`` and
747 ``Unknown``, and ``list`` is the list of people with those genders.
749 Note that ``{% regroup %}`` does not work when the list to be grouped is not
750 sorted by the key you are grouping by!  This means that if your list of people
751 was not sorted by gender, you'd need to make sure it is sorted before using it,
752 i.e.::
754     {% regroup people|dictsort:"gender" by gender as grouped %}
756 spaceless
757 ~~~~~~~~~
759 Normalizes whitespace between HTML tags to a single space. This includes tab
760 characters and newlines.
762 Example usage::
764     {% spaceless %}
765         <p>
766             <a href="foo/">Foo</a>
767         </p>
768     {% endspaceless %}
770 This example would return this HTML::
772     <p> <a href="foo/">Foo</a> </p>
774 Only space between *tags* is normalized -- not space between tags and text. In
775 this example, the space around ``Hello`` won't be stripped::
777     {% spaceless %}
778         <strong>
779             Hello
780         </strong>
781     {% endspaceless %}
786 Output the contents of a given file into the page.
788 Like a simple "include" tag, ``{% ssi %}`` includes the contents of another
789 file -- which must be specified using an absolute path -- in the current
790 page::
792     {% ssi /home/html/ljworld.com/includes/right_generic.html %}
794 If the optional "parsed" parameter is given, the contents of the included
795 file are evaluated as template code, within the current context::
797     {% ssi /home/html/ljworld.com/includes/right_generic.html parsed %}
799 Note that if you use ``{% ssi %}``, you'll need to define
800 `ALLOWED_INCLUDE_ROOTS`_ in your Django settings, as a security measure.
802 See also: ``{% include %}``.
804 .. _ALLOWED_INCLUDE_ROOTS: ../settings/#allowed-include-roots
806 templatetag
807 ~~~~~~~~~~~
809 Output one of the syntax characters used to compose template tags.
811 Since the template system has no concept of "escaping", to display one of the
812 bits used in template tags, you must use the ``{% templatetag %}`` tag.
814 The argument tells which template bit to output:
816     ==================  =======
817     Argument            Outputs
818     ==================  =======
819     ``openblock``       ``{%``
820     ``closeblock``      ``%}``
821     ``openvariable``    ``{{``
822     ``closevariable``   ``}}``
823     ``openbrace``       ``{``
824     ``closebrace``      ``}``
825     ``opencomment``     ``{#``
826     ``closecomment``    ``#}``
827     ==================  =======
832 **Note that the syntax for this tag may change in the future, as we make it more robust.**
834 Returns an absolute URL (i.e., a URL without the domain name) matching a given
835 view function and optional parameters. This is a way to output links without
836 violating the DRY principle by having to hard-code URLs in your templates::
838     {% url path.to.some_view arg1,arg2,name1=value1 %}
840 The first argument is a path to a view function in the format
841 ``package.package.module.function``. Additional arguments are optional and
842 should be comma-separated values that will be used as positional and keyword
843 arguments in the URL. All arguments required by the URLconf should be present.
845 For example, suppose you have a view, ``app_name.client``, whose URLconf takes
846 a client ID. The URLconf line might look like this::
848     ('^client/(\d+)/$', 'app_name.client')
850 If this app's URLconf is included into the project's URLconf under a path
851 such as this::
853     ('^clients/', include('project_name.app_name.urls'))
855 ...then, in a template, you can create a link to this view like this::
857     {% url app_name.client client.id %}
859 The template tag will output the string ``/clients/client/123/``.
861 widthratio
862 ~~~~~~~~~~
864 For creating bar charts and such, this tag calculates the ratio of a given value
865 to a maximum value, and then applies that ratio to a constant.
867 For example::
869     <img src="bar.gif" height="10" width="{% widthratio this_value max_value 100 %}" />
871 Above, if ``this_value`` is 175 and ``max_value`` is 200, the the image in the
872 above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5
873 which is rounded up to 88).
875 Built-in filter reference
876 -------------------------
881 Adds the arg to the value.
883 addslashes
884 ~~~~~~~~~~
886 Adds slashes. Useful for passing strings to JavaScript, for example.
889 capfirst
890 ~~~~~~~~
892 Capitalizes the first character of the value.
894 center
895 ~~~~~~
897 Centers the value in a field of a given width.
902 Removes all values of arg from the given string.
904 date
905 ~~~~
907 Formats a date according to the given format (same as the ``now`` tag).
909 default
910 ~~~~~~~
912 If value is unavailable, use given default.
914 default_if_none
915 ~~~~~~~~~~~~~~~
917 If value is ``None``, use given default.
919 dictsort
920 ~~~~~~~~
922 Takes a list of dicts, returns that list sorted by the property given in the
923 argument.
925 dictsortreversed
926 ~~~~~~~~~~~~~~~~
928 Takes a list of dicts, returns that list sorted in reverse order by the
929 property given in the argument.
931 divisibleby
932 ~~~~~~~~~~~
934 Returns true if the value is divisible by the argument.
936 escape
937 ~~~~~~
939 Escapes a string's HTML. Specifically, it makes these replacements:
941     * ``"&"`` to ``"&amp;"``
942     * ``<`` to ``"&lt;"``
943     * ``>`` to ``"&gt;"``
944     * ``'"'`` (double quote) to ``'&quot;'``
945     * ``"'"`` (single quote) to ``'&#39;'``
947 filesizeformat
948 ~~~~~~~~~~~~~~
950 Format the value like a 'human-readable' file size (i.e. ``'13 KB'``,
951 ``'4.1 MB'``, ``'102 bytes'``, etc).
953 first
954 ~~~~~
956 Returns the first item in a list.
958 fix_ampersands
959 ~~~~~~~~~~~~~~
961 Replaces ampersands with ``&amp;`` entities.
963 floatformat
964 ~~~~~~~~~~~
966 When used without an argument, rounds a floating-point number to one decimal
967 place -- but only if there's a decimal part to be displayed. For example:
969     * ``36.123`` gets converted to ``36.1``
970     * ``36.15`` gets converted to ``36.2``
971     * ``36`` gets converted to ``36``
973 If used with a numeric integer argument, ``floatformat`` rounds a number to that 
974 many decimal places.  For example:
976     * ``36.1234`` with floatformat:3 gets converted to ``36.123``
977     * ``36`` with floatformat:4 gets converted to ``36.0000``
979 If the argument passed to ``floatformat`` is negative, it will round a number to
980 that many decimal places -- but only if there's a decimal part to be displayed.
981 For example:
983     * ``36.1234`` with floatformat:-3 gets converted to ``36.123``
984     * ``36`` with floatformat:-4 gets converted to ``36``
986 Using ``floatformat`` with no argument is equivalent to using ``floatformat`` with 
987 an argument of ``-1``.
989 get_digit
990 ~~~~~~~~~
992 Given a whole number, returns the requested digit of it, where 1 is the
993 right-most digit, 2 is the second-right-most digit, etc. Returns the original
994 value for invalid input (if input or argument is not an integer, or if argument
995 is less than 1). Otherwise, output is always an integer.
997 join
998 ~~~~
1000 Joins a list with a string, like Python's ``str.join(list)``.
1002 length
1003 ~~~~~~
1005 Returns the length of the value. Useful for lists.
1007 length_is
1008 ~~~~~~~~~
1010 Returns a boolean of whether the value's length is the argument.
1012 linebreaks
1013 ~~~~~~~~~~
1015 Converts newlines into ``<p>`` and ``<br />`` tags.
1017 linebreaksbr
1018 ~~~~~~~~~~~~
1020 Converts newlines into ``<br />`` tags.
1022 linenumbers
1023 ~~~~~~~~~~~
1025 Displays text with line numbers.
1027 ljust
1028 ~~~~~
1030 Left-aligns the value in a field of a given width.
1032 **Argument:** field size
1034 lower
1035 ~~~~~
1037 Converts a string into all lowercase.
1039 make_list
1040 ~~~~~~~~~
1042 Returns the value turned into a list. For an integer, it's a list of
1043 digits. For a string, it's a list of characters.
1045 phone2numeric
1046 ~~~~~~~~~~~~~
1048 Converts a phone number (possibly containing letters) to its numerical
1049 equivalent. For example, ``'800-COLLECT'`` will be converted to
1050 ``'800-2655328'``.
1052 The input doesn't have to be a valid phone number. This will happily convert
1053 any string.
1055 pluralize
1056 ~~~~~~~~~
1058 Returns a plural suffix if the value is not 1. By default, this suffix is ``'s'``.
1060 Example::
1062     You have {{ num_messages }} message{{ num_messages|pluralize }}.
1064 For words that require a suffix other than ``'s'``, you can provide an alternate
1065 suffix as a parameter to the filter.
1067 Example::
1069     You have {{ num_walruses }} walrus{{ num_walrus|pluralize:"es" }}.
1071 For words that don't pluralize by simple suffix, you can specify both a
1072 singular and plural suffix, separated by a comma.
1074 Example::
1076     You have {{ num_cherries }} cherr{{ num_cherries|pluralize:"y,ies" }}.
1078 pprint
1079 ~~~~~~
1081 A wrapper around pprint.pprint -- for debugging, really.
1083 random
1084 ~~~~~~
1086 Returns a random item from the list.
1088 removetags
1089 ~~~~~~~~~~
1091 Removes a space separated list of [X]HTML tags from the output.
1093 rjust
1094 ~~~~~
1096 Right-aligns the value in a field of a given width.
1098 **Argument:** field size
1100 slice
1101 ~~~~~
1103 Returns a slice of the list.
1105 Uses the same syntax as Python's list slicing. See
1106 http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice
1107 for an introduction.
1109 Example: ``{{ some_list|slice:":2" }}``
1111 slugify
1112 ~~~~~~~
1114 Converts to lowercase, removes non-word characters (alphanumerics and
1115 underscores) and converts spaces to hyphens. Also strips leading and trailing
1116 whitespace.
1118 stringformat
1119 ~~~~~~~~~~~~
1121 Formats the variable according to the argument, a string formatting specifier.
1122 This specifier uses Python string formating syntax, with the exception that
1123 the leading "%" is dropped.
1125 See http://docs.python.org/lib/typesseq-strings.html for documentation of
1126 Python string formatting
1128 striptags
1129 ~~~~~~~~~
1131 Strips all [X]HTML tags.
1133 time
1134 ~~~~
1136 Formats a time according to the given format (same as the ``now`` tag).
1138 timesince
1139 ~~~~~~~~~
1141 Formats a date as the time since that date (i.e. "4 days, 6 hours").
1143 Takes an optional argument that is a variable containing the date to use as
1144 the comparison point (without the argument, the comparison point is *now*).
1145 For example, if ``blog_date`` is a date instance representing midnight on 1
1146 June 2006, and ``comment_date`` is a date instance for 08:00 on 1 June 2006,
1147 then ``{{ comment_date|timesince:blog_date }}`` would return "8 hours".
1149 timeuntil
1150 ~~~~~~~~~
1152 Similar to ``timesince``, except that it measures the time from now until the
1153 given date or datetime. For example, if today is 1 June 2006 and
1154 ``conference_date`` is a date instance holding 29 June 2006, then
1155 ``{{ conference_date|timeuntil }}`` will return "28 days".
1157 Takes an optional argument that is a variable containing the date to use as
1158 the comparison point (instead of *now*). If ``from_date`` contains 22 June
1159 2006, then ``{{ conference_date|timeuntil:from_date }}`` will return "7 days".
1161 title
1162 ~~~~~
1164 Converts a string into titlecase.
1166 truncatewords
1167 ~~~~~~~~~~~~~
1169 Truncates a string after a certain number of words.
1171 **Argument:** Number of words to truncate after
1173 truncatewords_html
1174 ~~~~~~~~~~~~~~~~~~
1176 Similar to ``truncatewords``, except that it is aware of HTML tags. Any tags
1177 that are opened in the string and not closed before the truncation point, are
1178 closed immediately after the truncation.
1180 This is less efficient than ``truncatewords``, so should only be used when it
1181 is being passed HTML text.
1183 unordered_list
1184 ~~~~~~~~~~~~~~
1186 Recursively takes a self-nested list and returns an HTML unordered list --
1187 WITHOUT opening and closing <ul> tags.
1189 The list is assumed to be in the proper format. For example, if ``var`` contains
1190 ``['States', [['Kansas', [['Lawrence', []], ['Topeka', []]]], ['Illinois', []]]]``,
1191 then ``{{ var|unordered_list }}`` would return::
1193     <li>States
1194     <ul>
1195             <li>Kansas
1196             <ul>
1197                     <li>Lawrence</li>
1198                     <li>Topeka</li>
1199             </ul>
1200             </li>
1201             <li>Illinois</li>
1202     </ul>
1203     </li>
1205 upper
1206 ~~~~~
1208 Converts a string into all uppercase.
1210 urlencode
1211 ~~~~~~~~~
1213 Escapes a value for use in a URL.
1215 urlize
1216 ~~~~~~
1218 Converts URLs in plain text into clickable links.
1220 urlizetrunc
1221 ~~~~~~~~~~~
1223 Converts URLs into clickable links, truncating URLs to the given character limit.
1225 **Argument:** Length to truncate URLs to
1227 wordcount
1228 ~~~~~~~~~
1230 Returns the number of words.
1232 wordwrap
1233 ~~~~~~~~
1235 Wraps words at specified line length.
1237 **Argument:** number of characters at which to wrap the text
1239 yesno
1240 ~~~~~
1242 Given a string mapping values for true, false and (optionally) None,
1243 returns one of those strings according to the value:
1245 ==========  ======================  ==================================
1246 Value       Argument                Outputs
1247 ==========  ======================  ==================================
1248 ``True``    ``"yeah,no,maybe"``     ``yeah``
1249 ``False``   ``"yeah,no,maybe"``     ``no``
1250 ``None``    ``"yeah,no,maybe"``     ``maybe``
1251 ``None``    ``"yeah,no"``           ``"no"`` (converts None to False
1252                                     if no mapping for None is given)
1253 ==========  ======================  ==================================
1255 Other tags and filter libraries
1256 ===============================
1258 Django comes with a couple of other template-tag libraries that you have to
1259 enable explicitly in your ``INSTALLED_APPS`` setting and enable in your
1260 template with the ``{% load %}`` tag.
1262 django.contrib.humanize
1263 -----------------------
1265 A set of Django template filters useful for adding a "human touch" to data. See
1266 the `humanize documentation`_.
1268 .. _humanize documentation: ../add_ons/#humanize
1270 django.contrib.markup
1271 ---------------------
1273 A collection of template filters that implement these common markup languages:
1275     * Textile
1276     * Markdown
1277     * ReST (ReStructured Text)