1 ==================================================
2 The Django template language: For template authors
3 ==================================================
5 This document explains the language syntax of the Django template system. If
6 you're looking for a more technical perspective on how it works and how to
7 extend it, see `The Django template language: For Python programmers`_.
9 Django's template language is designed to strike a balance between power and
10 ease. It's designed to feel comfortable to those used to working with HTML. If
11 you have any exposure to other text-based template languages, such as Smarty_
12 or CheetahTemplate_, you should feel right at home with Django's templates.
14 .. admonition:: Philosophy
16 If you have a background in programming, or if you're used to languages
17 like PHP which mix programming code directly into HTML, you'll want to
18 bear in mind that the Django template system is not simply Python embedded
19 into HTML. This is by design: the template system is meant to express
20 presentation, not program logic.
22 The Django template system provides tags which function similarly to some
23 programming constructs -- an ``{% if %}`` tag for boolean tests, a ``{%
24 for %}`` tag for looping, etc. -- but these are not simply executed as the
25 corresponding Python code, and the template system will not execute
26 arbitrary Python expressions. Only the tags, filters and syntax listed
27 below are supported by default (although you can add `your own
28 extensions`_ to the template language as needed).
30 .. _`The Django template language: For Python programmers`: ../templates_python/
31 .. _Smarty: http://smarty.php.net/
32 .. _CheetahTemplate: http://www.cheetahtemplate.org/
33 .. _your own extensions: ../templates_python/#extending-the-template-system
38 A template is simply a text file. It can generate any text-based format (HTML,
41 A template contains **variables**, which get replaced with values when the
42 template is evaluated, and **tags**, which control the logic of the template.
44 Below is a minimal template that illustrates a few basics. Each element will be
45 explained later in this document.::
47 {% extends "base_generic.html" %}
49 {% block title %}{{ section.title }}{% endblock %}
52 <h1>{{ section.title }}</h1>
54 {% for story in story_list %}
56 <a href="{{ story.get_absolute_url }}">
57 {{ story.headline|upper }}
60 <p>{{ story.tease|truncatewords:"100" }}</p>
64 .. admonition:: Philosophy
66 Why use a text-based template instead of an XML-based one (like Zope's
67 TAL)? We wanted Django's template language to be usable for more than
68 just XML/HTML templates. At World Online, we use it for e-mails,
69 JavaScript and CSV. You can use the template language for any text-based
72 Oh, and one more thing: Making humans edit XML is sadistic!
77 Variables look like this: ``{{ variable }}``. When the template engine
78 encounters a variable, it evaluates that variable and replaces it with the
81 Use a dot (``.``) to access attributes of a variable.
83 .. admonition:: Behind the scenes
85 Technically, when the template system encounters a dot, it tries the
86 following lookups, in this order:
93 In the above example, ``{{ section.title }}`` will be replaced with the
94 ``title`` attribute of the ``section`` object.
96 If you use a variable that doesn't exist, the template system will insert
97 the value of the ``TEMPLATE_STRING_IF_INVALID`` setting, which is set to ``''``
98 (the empty string) by default.
100 See `Using the built-in reference`_, below, for help on finding what variables
101 are available in a given template.
106 You can modify variables for display by using **filters**.
108 Filters look like this: ``{{ name|lower }}``. This displays the value of the
109 ``{{ name }}`` variable after being filtered through the ``lower`` filter,
110 which converts text to lowercase. Use a pipe (``|``) to apply a filter.
112 Filters can be "chained." The output of one filter is applied to the next.
113 ``{{ text|escape|linebreaks }}`` is a common idiom for escaping text contents,
114 then converting line breaks to ``<p>`` tags.
116 Some filters take arguments. A filter argument looks like this: ``{{
117 bio|truncatewords:30 }}``. This will display the first 30 words of the ``bio``
120 Filter arguments that contain spaces must be quoted; for example, to join a list
121 with commas and spaced you'd use ``{{ list|join:", " }}``.
123 The `Built-in filter reference`_ below describes all the built-in filters.
128 Tags look like this: ``{% tag %}``. Tags are more complex than variables: Some
129 create text in the output, some control flow by performing loops or logic, and
130 some load external information into the template to be used by later variables.
132 Some tags require beginning and ending tags (i.e.
133 ``{% tag %} ... tag contents ... {% endtag %}``). The `Built-in tag reference`_
134 below describes all the built-in tags. You can create your own tags, if you
135 know how to write Python code.
140 To comment-out part of a line in a template, use the comment syntax: ``{# #}``.
142 For example, this template would render as ``'hello'``::
146 A comment can contain any template code, invalid or not. For example::
148 {# {% if foo %}bar{% else %} #}
150 This syntax can only be used for single-line comments (no newlines are
151 permitted between the ``{#`` and ``#}`` delimiters). If you need to comment
152 out a multiline portion of the template, see the ``comment`` tag, below__.
159 The most powerful -- and thus the most complex -- part of Django's template
160 engine is template inheritance. Template inheritance allows you to build a base
161 "skeleton" template that contains all the common elements of your site and
162 defines **blocks** that child templates can override.
164 It's easiest to understand template inheritance by starting with an example::
166 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
167 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
168 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
170 <link rel="stylesheet" href="style.css" />
171 <title>{% block title %}My amazing site{% endblock %}</title>
178 <li><a href="/">Home</a></li>
179 <li><a href="/blog/">Blog</a></li>
185 {% block content %}{% endblock %}
190 This template, which we'll call ``base.html``, defines a simple HTML skeleton
191 document that you might use for a simple two-column page. It's the job of
192 "child" templates to fill the empty blocks with content.
194 In this example, the ``{% block %}`` tag defines three blocks that child
195 templates can fill in. All the ``block`` tag does is to tell the template
196 engine that a child template may override those portions of the template.
198 A child template might look like this::
200 {% extends "base.html" %}
202 {% block title %}My amazing blog{% endblock %}
205 {% for entry in blog_entries %}
206 <h2>{{ entry.title }}</h2>
207 <p>{{ entry.body }}</p>
211 The ``{% extends %}`` tag is the key here. It tells the template engine that
212 this template "extends" another template. When the template system evaluates
213 this template, first it locates the parent -- in this case, "base.html".
215 At that point, the template engine will notice the three ``{% block %}`` tags
216 in ``base.html`` and replace those blocks with the contents of the child
217 template. Depending on the value of ``blog_entries``, the output might look
220 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
221 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
222 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
224 <link rel="stylesheet" href="style.css" />
225 <title>My amazing blog</title>
231 <li><a href="/">Home</a></li>
232 <li><a href="/blog/">Blog</a></li>
238 <p>This is my first entry.</p>
241 <p>This is my second entry.</p>
246 Note that since the child template didn't define the ``sidebar`` block, the
247 value from the parent template is used instead. Content within a ``{% block %}``
248 tag in a parent template is always used as a fallback.
250 You can use as many levels of inheritance as needed. One common way of using
251 inheritance is the following three-level approach:
253 * Create a ``base.html`` template that holds the main look-and-feel of your
255 * Create a ``base_SECTIONNAME.html`` template for each "section" of your
256 site. For example, ``base_news.html``, ``base_sports.html``. These
257 templates all extend ``base.html`` and include section-specific
259 * Create individual templates for each type of page, such as a news
260 article or blog entry. These templates extend the appropriate section
263 This approach maximizes code reuse and makes it easy to add items to shared
264 content areas, such as section-wide navigation.
266 Here are some tips for working with inheritance:
268 * If you use ``{% extends %}`` in a template, it must be the first template
269 tag in that template. Template inheritance won't work, otherwise.
271 * More ``{% block %}`` tags in your base templates are better. Remember,
272 child templates don't have to define all parent blocks, so you can fill
273 in reasonable defaults in a number of blocks, then only define the ones
274 you need later. It's better to have more hooks than fewer hooks.
276 * If you find yourself duplicating content in a number of templates, it
277 probably means you should move that content to a ``{% block %}`` in a
280 * If you need to get the content of the block from the parent template,
281 the ``{{ block.super }}`` variable will do the trick. This is useful
282 if you want to add to the contents of a parent block instead of
283 completely overriding it.
285 * For extra readability, you can optionally give a *name* to your
286 ``{% endblock %}`` tag. For example::
290 {% endblock content %}
292 In larger templates, this technique helps you see which ``{% block %}``
293 tags are being closed.
295 Finally, note that you can't define multiple ``{% block %}`` tags with the same
296 name in the same template. This limitation exists because a block tag works in
297 "both" directions. That is, a block tag doesn't just provide a hole to fill --
298 it also defines the content that fills the hole in the *parent*. If there were
299 two similarly-named ``{% block %}`` tags in a template, that template's parent
300 wouldn't know which one of the blocks' content to use.
302 Using the built-in reference
303 ============================
305 Django's admin interface includes a complete reference of all template tags and
306 filters available for a given site. To see it, go to your admin interface and
307 click the "Documentation" link in the upper right of the page.
309 The reference is divided into 4 sections: tags, filters, models, and views.
311 The **tags** and **filters** sections describe all the built-in tags (in fact,
312 the tag and filter references below come directly from those pages) as well as
313 any custom tag or filter libraries available.
315 The **views** page is the most valuable. Each URL in your site has a separate
316 entry here, and clicking on a URL will show you:
318 * The name of the view function that generates that view.
319 * A short description of what the view does.
320 * The **context**, or a list of variables available in the view's template.
321 * The name of the template or templates that are used for that view.
323 Each view documentation page also has a bookmarklet that you can use to jump
324 from any page to the documentation page for that view.
326 Because Django-powered sites usually use database objects, the **models**
327 section of the documentation page describes each type of object in the system
328 along with all the fields available on that object.
330 Taken together, the documentation pages should tell you every tag, filter,
331 variable and object available to you in a given template.
333 Custom tag and filter libraries
334 ===============================
336 Certain applications provide custom tag and filter libraries. To access them in
337 a template, use the ``{% load %}`` tag::
341 {% comment_form for blogs.entries entry.id with is_public yes %}
343 In the above, the ``load`` tag loads the ``comments`` tag library, which then
344 makes the ``comment_form`` tag available for use. Consult the documentation
345 area in your admin to find the list of custom libraries in your installation.
347 The ``{% load %}`` tag can take multiple library names, separated by spaces.
350 {% load comments i18n %}
352 Custom libraries and template inheritance
353 -----------------------------------------
355 When you load a custom tag or filter library, the tags/filters are only made
356 available to the current template -- not any parent or child templates along
357 the template-inheritance path.
359 For example, if a template ``foo.html`` has ``{% load comments %}``, a child
360 template (e.g., one that has ``{% extends "foo.html" %}``) will *not* have
361 access to the comments template tags and filters. The child template is
362 responsible for its own ``{% load comments %}``.
364 This is a feature for the sake of maintainability and sanity.
366 Built-in tag and filter reference
367 =================================
369 For those without an admin site available, reference for the stock tags and
370 filters follows. Because Django is highly customizable, the reference in your
371 admin should be considered the final word on what tags and filters are
372 available, and what they do.
374 Built-in tag reference
375 ----------------------
380 Define a block that can be overridden by child templates. See
381 `Template inheritance`_ for more information.
386 Ignore everything between ``{% comment %}`` and ``{% endcomment %}``
391 **Changed in Django development version**
392 Cycle among the given strings or variables each time this tag is encountered.
394 Within a loop, cycles among the given strings/variables each time through the
397 {% for o in some_list %}
398 <tr class="{% cycle 'row1' 'row2' rowvar %}">
403 Outside of a loop, give the values a unique name the first time you call it,
404 then use that name each successive time through::
406 <tr class="{% cycle 'row1' 'row2' rowvar as rowcolors %}">...</tr>
407 <tr class="{% cycle rowcolors %}">...</tr>
408 <tr class="{% cycle rowcolors %}">...</tr>
410 You can use any number of values, separated by spaces. Values enclosed in
411 single (') or double quotes (") are treated as string literals, while values
412 without quotes are assumed to refer to context variables.
414 You can also separate values with commas::
416 {% cycle row1,row2,row3 %}
418 In this syntax, each value will be interpreted as literal text. The
419 comma-based syntax exists for backwards-compatibility, and should not be
420 used for new projects.
425 Output a whole load of debugging information, including the current context and
431 Signal that this template extends a parent template.
433 This tag can be used in two ways:
435 * ``{% extends "base.html" %}`` (with quotes) uses the literal value
436 ``"base.html"`` as the name of the parent template to extend.
438 * ``{% extends variable %}`` uses the value of ``variable``. If the variable
439 evaluates to a string, Django will use that string as the name of the
440 parent template. If the variable evaluates to a ``Template`` object,
441 Django will use that object as the parent template.
443 See `Template inheritance`_ for more information.
448 Filter the contents of the variable through variable filters.
450 Filters can also be piped through each other, and they can have arguments --
451 just like in variable syntax.
455 {% filter escape|lower %}
456 This text will be HTML-escaped, and will appear in all lowercase.
462 Outputs the first variable passed that is not False. Outputs nothing if all the
463 passed variables are False.
467 {% firstof var1 var2 var3 %}
469 This is equivalent to::
473 {% else %}{% if var2 %}
475 {% else %}{% if var3 %}
477 {% endif %}{% endif %}{% endif %}
482 Loop over each item in an array. For example, to display a list of athletes
483 provided in ``athlete_list``::
486 {% for athlete in athlete_list %}
487 <li>{{ athlete.name }}</li>
491 You can loop over a list in reverse by using ``{% for obj in list reversed %}``.
493 **New in Django development version**
494 If you need to loop over a list of lists, you can unpack the values
495 in eachs sub-list into a set of known names. For example, if your context contains
496 a list of (x,y) coordinates called ``points``, you could use the following
497 to output the list of points::
499 {% for x, y in points %}
500 There is a point at {{ x }},{{ y }}
503 This can also be useful if you need to access the items in a dictionary.
504 For example, if your context contained a dictionary ``data``, the following
505 would display the keys and values of the dictionary::
507 {% for key, value in data.items %}
508 {{ key }}: {{ value }}
511 The for loop sets a number of variables available within the loop:
513 ========================== ================================================
515 ========================== ================================================
516 ``forloop.counter`` The current iteration of the loop (1-indexed)
517 ``forloop.counter0`` The current iteration of the loop (0-indexed)
518 ``forloop.revcounter`` The number of iterations from the end of the
520 ``forloop.revcounter0`` The number of iterations from the end of the
522 ``forloop.first`` True if this is the first time through the loop
523 ``forloop.last`` True if this is the last time through the loop
524 ``forloop.parentloop`` For nested loops, this is the loop "above" the
526 ========================== ================================================
531 The ``{% if %}`` tag evaluates a variable, and if that variable is "true" (i.e.
532 exists, is not empty, and is not a false boolean value) the contents of the
535 {% if athlete_list %}
536 Number of athletes: {{ athlete_list|length }}
541 In the above, if ``athlete_list`` is not empty, the number of athletes will be
542 displayed by the ``{{ athlete_list|length }}`` variable.
544 As you can see, the ``if`` tag can take an optional ``{% else %}`` clause that
545 will be displayed if the test fails.
547 ``if`` tags may use ``and``, ``or`` or ``not`` to test a number of variables or
548 to negate a given variable::
550 {% if athlete_list and coach_list %}
551 Both athletes and coaches are available.
554 {% if not athlete_list %}
555 There are no athletes.
558 {% if athlete_list or coach_list %}
559 There are some athletes or some coaches.
562 {% if not athlete_list or coach_list %}
563 There are no athletes or there are some coaches (OK, so
564 writing English translations of boolean logic sounds
565 stupid; it's not our fault).
568 {% if athlete_list and not coach_list %}
569 There are some athletes and absolutely no coaches.
572 ``if`` tags don't allow ``and`` and ``or`` clauses within the same tag, because
573 the order of logic would be ambiguous. For example, this is invalid::
575 {% if athlete_list and coach_list or cheerleader_list %}
577 If you need to combine ``and`` and ``or`` to do advanced logic, just use nested
578 ``if`` tags. For example::
580 {% if athlete_list %}
581 {% if coach_list or cheerleader_list %}
582 We have athletes, and either coaches or cheerleaders!
586 Multiple uses of the same logical operator are fine, as long as you use the
587 same operator. For example, this is valid::
589 {% if athlete_list or coach_list or parent_list or teacher_list %}
594 Check if a value has changed from the last iteration of a loop.
596 The 'ifchanged' block tag is used within a loop. It has two possible uses.
598 1. Checks its own rendered contents against its previous state and only
599 displays the content if it has changed. For example, this displays a list of
600 days, only displaying the month if it changes::
602 <h1>Archive for {{ year }}</h1>
604 {% for date in days %}
605 {% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %}
606 <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a>
609 2. If given a variable, check whether that variable has changed. For
610 example, the following shows the date every time it changes, but
611 only shows the hour if both the hour and the date has changed::
613 {% for date in days %}
614 {% ifchanged date.date %} {{ date.date }} {% endifchanged %}
615 {% ifchanged date.hour date.date %}
623 Output the contents of the block if the two arguments equal each other.
627 {% ifequal user.id comment.user_id %}
631 As in the ``{% if %}`` tag, an ``{% else %}`` clause is optional.
633 The arguments can be hard-coded strings, so the following is valid::
635 {% ifequal user.username "adrian" %}
639 It is only possible to compare an argument to template variables or strings.
640 You cannot check for equality with Python objects such as ``True`` or
641 ``False``. If you need to test if something is true or false, use the ``if``
647 Just like ``ifequal``, except it tests that the two arguments are not equal.
652 Loads a template and renders it with the current context. This is a way of
653 "including" other templates within a template.
655 The template name can either be a variable or a hard-coded (quoted) string,
656 in either single or double quotes.
658 This example includes the contents of the template ``"foo/bar.html"``::
660 {% include "foo/bar.html" %}
662 This example includes the contents of the template whose name is contained in
663 the variable ``template_name``::
665 {% include template_name %}
667 An included template is rendered with the context of the template that's
668 including it. This example produces the output ``"Hello, John"``:
670 * Context: variable ``person`` is set to ``"john"``.
673 {% include "name_snippet.html" %}
675 * The ``name_snippet.html`` template::
679 See also: ``{% ssi %}``.
684 Load a custom template tag set.
686 See `Custom tag and filter libraries`_ for more information.
691 Display the date, formatted according to the given string.
693 Uses the same format as PHP's ``date()`` function (http://php.net/date)
694 with some custom extensions.
696 Available format strings:
698 ================ ======================================== =====================
699 Format character Description Example output
700 ================ ======================================== =====================
701 a ``'a.m.'`` or ``'p.m.'`` (Note that ``'a.m.'``
702 this is slightly different than PHP's
703 output, because this includes periods
704 to match Associated Press style.)
705 A ``'AM'`` or ``'PM'``. ``'AM'``
706 b Month, textual, 3 letters, lowercase. ``'jan'``
708 d Day of the month, 2 digits with ``'01'`` to ``'31'``
710 D Day of the week, textual, 3 letters. ``'Fri'``
711 f Time, in 12-hour hours and minutes, ``'1'``, ``'1:30'``
712 with minutes left off if they're zero.
713 Proprietary extension.
714 F Month, textual, long. ``'January'``
715 g Hour, 12-hour format without leading ``'1'`` to ``'12'``
717 G Hour, 24-hour format without leading ``'0'`` to ``'23'``
719 h Hour, 12-hour format. ``'01'`` to ``'12'``
720 H Hour, 24-hour format. ``'00'`` to ``'23'``
721 i Minutes. ``'00'`` to ``'59'``
723 j Day of the month without leading ``'1'`` to ``'31'``
725 l Day of the week, textual, long. ``'Friday'``
726 L Boolean for whether it's a leap year. ``True`` or ``False``
727 m Month, 2 digits with leading zeros. ``'01'`` to ``'12'``
728 M Month, textual, 3 letters. ``'Jan'``
729 n Month without leading zeros. ``'1'`` to ``'12'``
730 N Month abbreviation in Associated Press ``'Jan.'``, ``'Feb.'``, ``'March'``, ``'May'``
731 style. Proprietary extension.
732 O Difference to Greenwich time in hours. ``'+0200'``
733 P Time, in 12-hour hours, minutes and ``'1 a.m.'``, ``'1:30 p.m.'``, ``'midnight'``, ``'noon'``, ``'12:30 p.m.'``
734 'a.m.'/'p.m.', with minutes left off
735 if they're zero and the special-case
736 strings 'midnight' and 'noon' if
737 appropriate. Proprietary extension.
738 r RFC 822 formatted date. ``'Thu, 21 Dec 2000 16:01:07 +0200'``
739 s Seconds, 2 digits with leading zeros. ``'00'`` to ``'59'``
740 S English ordinal suffix for day of the ``'st'``, ``'nd'``, ``'rd'`` or ``'th'``
742 t Number of days in the given month. ``28`` to ``31``
743 T Time zone of this machine. ``'EST'``, ``'MDT'``
745 w Day of the week, digits without ``'0'`` (Sunday) to ``'6'`` (Saturday)
747 W ISO-8601 week number of year, with ``1``, ``23``
748 weeks starting on Monday.
749 y Year, 2 digits. ``'99'``
750 Y Year, 4 digits. ``'1999'``
751 z Day of the year. ``0`` to ``365``
752 Z Time zone offset in seconds. The ``-43200`` to ``43200``
753 offset for timezones west of UTC is
754 always negative, and for those east of
755 UTC is always positive.
756 ================ ======================================== =====================
760 It is {% now "jS F Y H:i" %}
762 Note that you can backslash-escape a format string if you want to use the
763 "raw" value. In this example, "f" is backslash-escaped, because otherwise
764 "f" is a format string that displays the time. The "o" doesn't need to be
765 escaped, because it's not a format character::
767 It is the {% now "jS o\f F" %}
769 This would display as "It is the 4th of September".
774 Regroup a list of alike objects by a common attribute.
776 This complex tag is best illustrated by use of an example: say that ``people``
777 is a list of people represented by dictionaries with ``first_name``,
778 ``last_name``, and ``gender`` keys::
781 {'first_name': 'George', 'last_name': 'Bush', 'gender': 'Male'},
782 {'first_name': 'Bill', 'last_name': 'Clinton', 'gender': 'Male'},
783 {'first_name': 'Margaret', 'last_name': 'Thatcher', 'gender': 'Female'},
784 {'first_name': 'Condoleezza', 'last_name': 'Rice', 'gender': 'Female'},
785 {'first_name': 'Pat', 'last_name': 'Smith', 'gender': 'Unknown'},
788 ...and you'd like to display a hierarchical list that is ordered by gender,
800 You can use the ``{% regroup %}`` tag to group the list of people by gender.
801 The following snippet of template code would accomplish this::
803 {% regroup people by gender as gender_list %}
806 {% for gender in gender_list %}
807 <li>{{ gender.grouper }}
809 {% for item in gender.list %}
810 <li>{{ item.first_name }} {{ item.last_name }}</li>
817 Let's walk through this example. ``{% regroup %}`` takes three arguments: the
818 list you want to regroup, the attribute to group by, and the name of the
819 resulting list. Here, we're regrouping the ``people`` list by the ``gender``
820 attribute and calling the result ``gender_list``.
822 ``{% regroup %}`` produces a list (in this case, ``gender_list``) of
823 **group objects**. Each group object has two attributes:
825 * ``grouper`` -- the item that was grouped by (e.g., the string "Male" or
827 * ``list`` -- a list of all items in this group (e.g., a list of all people
830 Note that ``{% regroup %}`` does not order its input! Our example relies on
831 the fact that the ``people`` list was ordered by ``gender`` in the first place.
832 If the ``people`` list did *not* order its members by ``gender``, the regrouping
833 would naively display more than one group for a single gender. For example,
834 say the ``people`` list was set to this (note that the males are not grouped
838 {'first_name': 'Bill', 'last_name': 'Clinton', 'gender': 'Male'},
839 {'first_name': 'Pat', 'last_name': 'Smith', 'gender': 'Unknown'},
840 {'first_name': 'Margaret', 'last_name': 'Thatcher', 'gender': 'Female'},
841 {'first_name': 'George', 'last_name': 'Bush', 'gender': 'Male'},
842 {'first_name': 'Condoleezza', 'last_name': 'Rice', 'gender': 'Female'},
845 With this input for ``people``, the example ``{% regroup %}`` template code
846 above would result in the following output:
859 The easiest solution to this gotcha is to make sure in your view code that the
860 data is ordered according to how you want to display it.
862 Another solution is to sort the data in the template using the ``dictsort``
863 filter, if your data is in a list of dictionaries::
865 {% regroup people|dictsort:"gender" by gender as gender_list %}
870 Removes whitespace between HTML tags. This includes tab
871 characters and newlines.
877 <a href="foo/">Foo</a>
881 This example would return this HTML::
883 <p><a href="foo/">Foo</a></p>
885 Only space between *tags* is removed -- not space between tags and text. In
886 this example, the space around ``Hello`` won't be stripped::
897 Output the contents of a given file into the page.
899 Like a simple "include" tag, ``{% ssi %}`` includes the contents of another
900 file -- which must be specified using an absolute path -- in the current
903 {% ssi /home/html/ljworld.com/includes/right_generic.html %}
905 If the optional "parsed" parameter is given, the contents of the included
906 file are evaluated as template code, within the current context::
908 {% ssi /home/html/ljworld.com/includes/right_generic.html parsed %}
910 Note that if you use ``{% ssi %}``, you'll need to define
911 `ALLOWED_INCLUDE_ROOTS`_ in your Django settings, as a security measure.
913 See also: ``{% include %}``.
915 .. _ALLOWED_INCLUDE_ROOTS: ../settings/#allowed-include-roots
920 Output one of the syntax characters used to compose template tags.
922 Since the template system has no concept of "escaping", to display one of the
923 bits used in template tags, you must use the ``{% templatetag %}`` tag.
925 The argument tells which template bit to output:
927 ================== =======
929 ================== =======
931 ``closeblock`` ``%}``
932 ``openvariable`` ``{{``
933 ``closevariable`` ``}}``
936 ``opencomment`` ``{#``
937 ``closecomment`` ``#}``
938 ================== =======
943 **Note that the syntax for this tag may change in the future, as we make it more robust.**
945 Returns an absolute URL (i.e., a URL without the domain name) matching a given
946 view function and optional parameters. This is a way to output links without
947 violating the DRY principle by having to hard-code URLs in your templates::
949 {% url path.to.some_view arg1,arg2,name1=value1 %}
951 The first argument is a path to a view function in the format
952 ``package.package.module.function``. Additional arguments are optional and
953 should be comma-separated values that will be used as positional and keyword
954 arguments in the URL. All arguments required by the URLconf should be present.
956 For example, suppose you have a view, ``app_views.client``, whose URLconf
957 takes a client ID (here, ``client()`` is a method inside the views file
958 ``app_views.py``). The URLconf line might look like this::
960 ('^client/(\d+)/$', 'app_views.client')
962 If this app's URLconf is included into the project's URLconf under a path
965 ('^clients/', include('project_name.app_name.urls'))
967 ...then, in a template, you can create a link to this view like this::
969 {% url app_views.client client.id %}
971 The template tag will output the string ``/clients/client/123/``.
973 **New in development version:** If you're using `named URL patterns`_,
974 you can refer to the name of the pattern in the ``url`` tag instead of
975 using the path to the view.
977 .. _named URL patterns: ../url_dispatch/#naming-url-patterns
982 For creating bar charts and such, this tag calculates the ratio of a given value
983 to a maximum value, and then applies that ratio to a constant.
987 <img src="bar.gif" height="10" width="{% widthratio this_value max_value 100 %}" />
989 Above, if ``this_value`` is 175 and ``max_value`` is 200, the the image in the
990 above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5
991 which is rounded up to 88).
996 **New in Django development version**
998 Caches a complex variable under a simpler name. This is useful when accessing
999 an "expensive" method (e.g., one that hits the database) multiple times.
1003 {% with business.employees.count as total %}
1004 {{ total }} employee{{ total|pluralize }}
1007 The populated variable (in the example above, ``total``) is only available
1008 between the ``{% with %}`` and ``{% endwith %}`` tags.
1010 Built-in filter reference
1011 -------------------------
1016 Adds the arg to the value.
1021 Adds slashes. Useful for passing strings to JavaScript, for example.
1027 Capitalizes the first character of the value.
1032 Centers the value in a field of a given width.
1037 Removes all values of arg from the given string.
1042 Formats a date according to the given format (same as the `now`_ tag).
1047 If value is unavailable, use given default.
1052 If value is ``None``, use given default.
1057 Takes a list of dictionaries, returns that list sorted by the key given in
1063 Takes a list of dictionaries, returns that list sorted in reverse order by the
1064 key given in the argument.
1069 Returns true if the value is divisible by the argument.
1074 Escapes a string's HTML. Specifically, it makes these replacements:
1076 * ``"&"`` to ``"&"``
1077 * ``<`` to ``"<"``
1078 * ``>`` to ``">"``
1079 * ``'"'`` (double quote) to ``'"'``
1080 * ``"'"`` (single quote) to ``'''``
1085 Format the value like a 'human-readable' file size (i.e. ``'13 KB'``,
1086 ``'4.1 MB'``, ``'102 bytes'``, etc).
1091 Returns the first item in a list.
1096 Replaces ampersands with ``&`` entities.
1101 When used without an argument, rounds a floating-point number to one decimal
1102 place -- but only if there's a decimal part to be displayed. For example:
1104 * ``36.123`` gets converted to ``36.1``
1105 * ``36.15`` gets converted to ``36.2``
1106 * ``36`` gets converted to ``36``
1108 If used with a numeric integer argument, ``floatformat`` rounds a number to that
1109 many decimal places. For example:
1111 * ``36.1234`` with floatformat:3 gets converted to ``36.123``
1112 * ``36`` with floatformat:4 gets converted to ``36.0000``
1114 If the argument passed to ``floatformat`` is negative, it will round a number to
1115 that many decimal places -- but only if there's a decimal part to be displayed.
1118 * ``36.1234`` with floatformat:-3 gets converted to ``36.123``
1119 * ``36`` with floatformat:-4 gets converted to ``36``
1121 Using ``floatformat`` with no argument is equivalent to using ``floatformat`` with
1122 an argument of ``-1``.
1127 Given a whole number, returns the requested digit of it, where 1 is the
1128 right-most digit, 2 is the second-right-most digit, etc. Returns the original
1129 value for invalid input (if input or argument is not an integer, or if argument
1130 is less than 1). Otherwise, output is always an integer.
1135 Converts an IRI (Internationalized Resource Identifier) to a string that is
1136 suitable for including in a URL. This is necessary if you're trying to use
1137 strings containing non-ASCII characters in a URL.
1139 It's safe to use this filter on a string that has already gone through the
1140 ``urlencode`` filter.
1145 Joins a list with a string, like Python's ``str.join(list)``.
1150 Returns the length of the value. Useful for lists.
1155 Returns a boolean of whether the value's length is the argument.
1160 Replaces line breaks in plain text with appropriate HTML; a single
1161 newline becomes an HTML line break (``<br />``) and a new line
1162 followed by a blank line becomes a paragraph break (``</p>``).
1167 Converts all newlines in a piece of plain text to HTML line breaks
1173 Displays text with line numbers.
1178 Left-aligns the value in a field of a given width.
1180 **Argument:** field size
1185 Converts a string into all lowercase.
1190 Returns the value turned into a list. For an integer, it's a list of
1191 digits. For a string, it's a list of characters.
1196 Converts a phone number (possibly containing letters) to its numerical
1197 equivalent. For example, ``'800-COLLECT'`` will be converted to
1200 The input doesn't have to be a valid phone number. This will happily convert
1206 Returns a plural suffix if the value is not 1. By default, this suffix is ``'s'``.
1210 You have {{ num_messages }} message{{ num_messages|pluralize }}.
1212 For words that require a suffix other than ``'s'``, you can provide an alternate
1213 suffix as a parameter to the filter.
1217 You have {{ num_walruses }} walrus{{ num_walrus|pluralize:"es" }}.
1219 For words that don't pluralize by simple suffix, you can specify both a
1220 singular and plural suffix, separated by a comma.
1224 You have {{ num_cherries }} cherr{{ num_cherries|pluralize:"y,ies" }}.
1229 A wrapper around pprint.pprint -- for debugging, really.
1234 Returns a random item from the list.
1239 Removes a space separated list of [X]HTML tags from the output.
1244 Right-aligns the value in a field of a given width.
1246 **Argument:** field size
1251 Returns a slice of the list.
1253 Uses the same syntax as Python's list slicing. See
1254 http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice
1255 for an introduction.
1257 Example: ``{{ some_list|slice:":2" }}``
1262 Converts to lowercase, removes non-word characters (alphanumerics and
1263 underscores) and converts spaces to hyphens. Also strips leading and trailing
1269 Formats the variable according to the argument, a string formatting specifier.
1270 This specifier uses Python string formating syntax, with the exception that
1271 the leading "%" is dropped.
1273 See http://docs.python.org/lib/typesseq-strings.html for documentation of
1274 Python string formatting
1279 Strips all [X]HTML tags.
1284 Formats a time according to the given format (same as the `now`_ tag).
1285 The time filter will only accept parameters in the format string that relate
1286 to the time of day, not the date (for obvious reasons). If you need to
1287 format a date, use the `date`_ filter.
1292 Formats a date as the time since that date (i.e. "4 days, 6 hours").
1294 Takes an optional argument that is a variable containing the date to use as
1295 the comparison point (without the argument, the comparison point is *now*).
1296 For example, if ``blog_date`` is a date instance representing midnight on 1
1297 June 2006, and ``comment_date`` is a date instance for 08:00 on 1 June 2006,
1298 then ``{{ comment_date|timesince:blog_date }}`` would return "8 hours".
1300 Minutes is the smallest unit used, and "0 minutes" will be returned for any
1301 date that is in the future relative to the comparison point.
1306 Similar to ``timesince``, except that it measures the time from now until the
1307 given date or datetime. For example, if today is 1 June 2006 and
1308 ``conference_date`` is a date instance holding 29 June 2006, then
1309 ``{{ conference_date|timeuntil }}`` will return "4 weeks".
1311 Takes an optional argument that is a variable containing the date to use as
1312 the comparison point (instead of *now*). If ``from_date`` contains 22 June
1313 2006, then ``{{ conference_date|timeuntil:from_date }}`` will return "1 week".
1315 Minutes is the smallest unit used, and "0 minutes" will be returned for any
1316 date that is in the past relative to the comparison point.
1321 Converts a string into titlecase.
1326 Truncates a string after a certain number of words.
1328 **Argument:** Number of words to truncate after
1333 Similar to ``truncatewords``, except that it is aware of HTML tags. Any tags
1334 that are opened in the string and not closed before the truncation point, are
1335 closed immediately after the truncation.
1337 This is less efficient than ``truncatewords``, so should only be used when it
1338 is being passed HTML text.
1343 Recursively takes a self-nested list and returns an HTML unordered list --
1344 WITHOUT opening and closing <ul> tags.
1346 **Changed in Django development version**
1348 The format accepted by ``unordered_list`` has changed to an easier to
1351 The list is assumed to be in the proper format. For example, if ``var`` contains
1352 ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then
1353 ``{{ var|unordered_list }}`` would return::
1367 Note: the previous more restrictive and verbose format is still supported:
1368 ``['States', [['Kansas', [['Lawrence', []], ['Topeka', []]]], ['Illinois', []]]]``,
1373 Converts a string into all uppercase.
1378 Escapes a value for use in a URL.
1383 Converts URLs in plain text into clickable links.
1385 Note that if ``urlize`` is applied to text that already contains HTML markup,
1386 things won't work as expected. Apply this filter only to *plain* text.
1391 Converts URLs into clickable links, truncating URLs longer than the given
1394 As with urlize_, this filter should only be applied to *plain* text.
1396 **Argument:** Length to truncate URLs to
1401 Returns the number of words.
1406 Wraps words at specified line length.
1408 **Argument:** number of characters at which to wrap the text
1413 Given a string mapping values for true, false and (optionally) None,
1414 returns one of those strings according to the value:
1416 ========== ====================== ==================================
1417 Value Argument Outputs
1418 ========== ====================== ==================================
1419 ``True`` ``"yeah,no,maybe"`` ``yeah``
1420 ``False`` ``"yeah,no,maybe"`` ``no``
1421 ``None`` ``"yeah,no,maybe"`` ``maybe``
1422 ``None`` ``"yeah,no"`` ``"no"`` (converts None to False
1423 if no mapping for None is given)
1424 ========== ====================== ==================================
1426 Other tags and filter libraries
1427 ===============================
1429 Django comes with a couple of other template-tag libraries that you have to
1430 enable explicitly in your ``INSTALLED_APPS`` setting and enable in your
1431 template with the ``{% load %}`` tag.
1433 django.contrib.humanize
1434 -----------------------
1436 A set of Django template filters useful for adding a "human touch" to data. See
1437 the `humanize documentation`_.
1439 .. _humanize documentation: ../add_ons/#humanize
1441 django.contrib.markup
1442 ---------------------
1444 A collection of template filters that implement these common markup languages:
1448 * ReST (ReStructured Text)
1450 See the `markup section`_ of the `add-ons documentation`_ for more
1453 .. _markup section: ../add_ons/#markup
1454 .. _add-ons documentation: ../add_ons/
1456 django.contrib.webdesign
1457 ------------------------
1459 A collection of template tags that can be useful while designing a website,
1460 such as a generator of Lorem Ipsum text. See the `webdesign documentation`_.
1462 .. _webdesign documentation: ../webdesign/