1 ============================
2 The Django template language
3 ============================
5 .. admonition:: About this document
7 This document explains the language syntax of the Django template system. If
8 you're looking for a more technical perspective on how it works and how to
9 extend it, see :doc:`/ref/templates/api`.
11 Django's template language is designed to strike a balance between power and
12 ease. It's designed to feel comfortable to those used to working with HTML. If
13 you have any exposure to other text-based template languages, such as Smarty_
14 or CheetahTemplate_, you should feel right at home with Django's templates.
16 .. admonition:: Philosophy
18 If you have a background in programming, or if you're used to languages
19 like PHP which mix programming code directly into HTML, you'll want to
20 bear in mind that the Django template system is not simply Python embedded
21 into HTML. This is by design: the template system is meant to express
22 presentation, not program logic.
24 The Django template system provides tags which function similarly to some
25 programming constructs -- an :ttag:`if` tag for boolean tests, a :ttag:`for`
26 tag for looping, etc. -- but these are not simply executed as the
27 corresponding Python code, and the template system will not execute
28 arbitrary Python expressions. Only the tags, filters and syntax listed below
29 are supported by default (although you can add :doc:`your own extensions
30 </howto/custom-template-tags>` to the template language as needed).
32 .. _`The Django template language: For Python programmers`: ../templates_python/
33 .. _Smarty: http://smarty.php.net/
34 .. _CheetahTemplate: http://www.cheetahtemplate.org/
39 .. highlightlang:: html+django
41 A template is simply a text file. It can generate any text-based format (HTML,
44 A template contains **variables**, which get replaced with values when the
45 template is evaluated, and **tags**, which control the logic of the template.
47 Below is a minimal template that illustrates a few basics. Each element will be
48 explained later in this document.::
50 {% extends "base_generic.html" %}
52 {% block title %}{{ section.title }}{% endblock %}
55 <h1>{{ section.title }}</h1>
57 {% for story in story_list %}
59 <a href="{{ story.get_absolute_url }}">
60 {{ story.headline|upper }}
63 <p>{{ story.tease|truncatewords:"100" }}</p>
67 .. admonition:: Philosophy
69 Why use a text-based template instead of an XML-based one (like Zope's
70 TAL)? We wanted Django's template language to be usable for more than
71 just XML/HTML templates. At World Online, we use it for emails,
72 JavaScript and CSV. You can use the template language for any text-based
75 Oh, and one more thing: Making humans edit XML is sadistic!
80 Variables look like this: ``{{ variable }}``. When the template engine
81 encounters a variable, it evaluates that variable and replaces it with the
82 result. Variable names consist of any combination of alphanumeric characters
83 and the underscore (``"_"``). The dot (``"."``) also appears in variable
84 sections, although that has a special meaning, as indicated below.
85 Importantly, *you cannot have spaces or punctuation characters in variable
88 Use a dot (``.``) to access attributes of a variable.
90 .. admonition:: Behind the scenes
92 Technically, when the template system encounters a dot, it tries the
93 following lookups, in this order:
100 This can cause some unexpected behavior with objects that override
101 dictionary lookup. For example, consider the following code snippet that
102 attempts to loop over a ``collections.defaultdict``::
104 {% for k, v in defaultdict.iteritems %}
105 Do something with k and v here...
108 Because dictionary lookup happens first, that behavior kicks in and provides
109 a default value instead of using the intended ``.iteritems()``
110 method. In this case, consider converting to a dictionary first.
112 In the above example, ``{{ section.title }}`` will be replaced with the
113 ``title`` attribute of the ``section`` object.
115 If you use a variable that doesn't exist, the template system will insert
116 the value of the :setting:`TEMPLATE_STRING_IF_INVALID` setting, which is set
117 to ``''`` (the empty string) by default.
119 Note that "bar" in a template expression like ``{{ foo.bar }}`` will be
120 interpreted as a literal string and not using the value of the variable "bar",
121 if one exists in the template context.
126 You can modify variables for display by using **filters**.
128 Filters look like this: ``{{ name|lower }}``. This displays the value of the
129 ``{{ name }}`` variable after being filtered through the :tfilter:`lower`
130 filter, which converts text to lowercase. Use a pipe (``|``) to apply a filter.
132 Filters can be "chained." The output of one filter is applied to the next.
133 ``{{ text|escape|linebreaks }}`` is a common idiom for escaping text contents,
134 then converting line breaks to ``<p>`` tags.
136 Some filters take arguments. A filter argument looks like this: ``{{
137 bio|truncatewords:30 }}``. This will display the first 30 words of the ``bio``
140 Filter arguments that contain spaces must be quoted; for example, to join a
141 list with commas and spaced you'd use ``{{ list|join:", " }}``.
143 Django provides about thirty built-in template filters. You can read all about
144 them in the :ref:`built-in filter reference <ref-templates-builtins-filters>`.
145 To give you a taste of what's available, here are some of the more commonly
146 used template filters:
149 If a variable is false or empty, use given default. Otherwise, use the
150 value of the variable
154 {{ value|default:"nothing" }}
156 If ``value`` isn't provided or is empty, the above will display
160 Returns the length of the value. This works for both strings and lists;
165 If ``value`` is ``['a', 'b', 'c', 'd']``, the output will be ``4``.
168 Strips all [X]HTML tags. For example::
170 {{ value|striptags }}
172 If ``value`` is ``"<b>Joel</b> <button>is</button> a
173 <span>slug</span>"``, the output will be ``"Joel is a slug"``.
175 Again, these are just a few examples; see the :ref:`built-in filter reference
176 <ref-templates-builtins-filters>` for the complete list.
178 You can also create your own custom template filters; see
179 :doc:`/howto/custom-template-tags`.
183 Django's admin interface can include a complete reference of all template
184 tags and filters available for a given site. See
185 :doc:`/ref/contrib/admin/admindocs`.
190 Tags look like this: ``{% tag %}``. Tags are more complex than variables: Some
191 create text in the output, some control flow by performing loops or logic, and
192 some load external information into the template to be used by later variables.
194 Some tags require beginning and ending tags (i.e. ``{% tag %} ... tag contents
197 Django ships with about two dozen built-in template tags. You can read all about
198 them in the :ref:`built-in tag reference <ref-templates-builtins-tags>`. To give
199 you a taste of what's available, here are some of the more commonly used
203 Loop over each item in an array. For example, to display a list of athletes
204 provided in ``athlete_list``::
207 {% for athlete in athlete_list %}
208 <li>{{ athlete.name }}</li>
212 :ttag:`if` and ``else``
213 Evaluates a variable, and if that variable is "true" the contents of the
214 block are displayed::
216 {% if athlete_list %}
217 Number of athletes: {{ athlete_list|length }}
222 In the above, if ``athlete_list`` is not empty, the number of athletes
223 will be displayed by the ``{{ athlete_list|length }}`` variable.
225 You can also use filters and various operators in the :ttag:`if` tag::
227 {% if athlete_list|length > 1 %}
228 Team: {% for athlete in athlete_list %} ... {% endfor %}
230 Athlete: {{ athlete_list.0.name }}
233 :ttag:`block` and :ttag:`extends`
234 Set up `template inheritance`_ (see below), a powerful way
235 of cutting down on "boilerplate" in templates.
237 Again, the above is only a selection of the whole list; see the :ref:`built-in
238 tag reference <ref-templates-builtins-tags>` for the complete list.
240 You can also create your own custom template tags; see
241 :doc:`/howto/custom-template-tags`.
245 Django's admin interface can include a complete reference of all template
246 tags and filters available for a given site. See
247 :doc:`/ref/contrib/admin/admindocs`.
252 To comment-out part of a line in a template, use the comment syntax: ``{# #}``.
254 For example, this template would render as ``'hello'``::
258 A comment can contain any template code, invalid or not. For example::
260 {# {% if foo %}bar{% else %} #}
262 This syntax can only be used for single-line comments (no newlines are permitted
263 between the ``{#`` and ``#}`` delimiters). If you need to comment out a
264 multiline portion of the template, see the :ttag:`comment` tag.
266 .. _template-inheritance:
271 The most powerful -- and thus the most complex -- part of Django's template
272 engine is template inheritance. Template inheritance allows you to build a base
273 "skeleton" template that contains all the common elements of your site and
274 defines **blocks** that child templates can override.
276 It's easiest to understand template inheritance by starting with an example::
281 <link rel="stylesheet" href="style.css" />
282 <title>{% block title %}My amazing site{% endblock %}</title>
289 <li><a href="/">Home</a></li>
290 <li><a href="/blog/">Blog</a></li>
296 {% block content %}{% endblock %}
301 This template, which we'll call ``base.html``, defines a simple HTML skeleton
302 document that you might use for a simple two-column page. It's the job of
303 "child" templates to fill the empty blocks with content.
305 In this example, the :ttag:`block` tag defines three blocks that child
306 templates can fill in. All the :ttag:`block` tag does is to tell the template
307 engine that a child template may override those portions of the template.
309 A child template might look like this::
311 {% extends "base.html" %}
313 {% block title %}My amazing blog{% endblock %}
316 {% for entry in blog_entries %}
317 <h2>{{ entry.title }}</h2>
318 <p>{{ entry.body }}</p>
322 The :ttag:`extends` tag is the key here. It tells the template engine that
323 this template "extends" another template. When the template system evaluates
324 this template, first it locates the parent -- in this case, "base.html".
326 At that point, the template engine will notice the three :ttag:`block` tags
327 in ``base.html`` and replace those blocks with the contents of the child
328 template. Depending on the value of ``blog_entries``, the output might look
334 <link rel="stylesheet" href="style.css" />
335 <title>My amazing blog</title>
341 <li><a href="/">Home</a></li>
342 <li><a href="/blog/">Blog</a></li>
348 <p>This is my first entry.</p>
351 <p>This is my second entry.</p>
356 Note that since the child template didn't define the ``sidebar`` block, the
357 value from the parent template is used instead. Content within a ``{% block %}``
358 tag in a parent template is always used as a fallback.
360 You can use as many levels of inheritance as needed. One common way of using
361 inheritance is the following three-level approach:
363 * Create a ``base.html`` template that holds the main look-and-feel of your
365 * Create a ``base_SECTIONNAME.html`` template for each "section" of your
366 site. For example, ``base_news.html``, ``base_sports.html``. These
367 templates all extend ``base.html`` and include section-specific
369 * Create individual templates for each type of page, such as a news
370 article or blog entry. These templates extend the appropriate section
373 This approach maximizes code reuse and makes it easy to add items to shared
374 content areas, such as section-wide navigation.
376 Here are some tips for working with inheritance:
378 * If you use :ttag:`{% extends %}<extends>` in a template, it must be the first template
379 tag in that template. Template inheritance won't work, otherwise.
381 * More :ttag:`{% block %}<block>` tags in your base templates are better. Remember,
382 child templates don't have to define all parent blocks, so you can fill
383 in reasonable defaults in a number of blocks, then only define the ones
384 you need later. It's better to have more hooks than fewer hooks.
386 * If you find yourself duplicating content in a number of templates, it
387 probably means you should move that content to a ``{% block %}`` in a
390 * If you need to get the content of the block from the parent template,
391 the ``{{ block.super }}`` variable will do the trick. This is useful
392 if you want to add to the contents of a parent block instead of
393 completely overriding it. Data inserted using ``{{ block.super }}`` will
394 not be automatically escaped (see the `next section`_), since it was
395 already escaped, if necessary, in the parent template.
397 * For extra readability, you can optionally give a *name* to your
398 ``{% endblock %}`` tag. For example::
402 {% endblock content %}
404 In larger templates, this technique helps you see which ``{% block %}``
405 tags are being closed.
407 Finally, note that you can't define multiple :ttag:`block` tags with the same
408 name in the same template. This limitation exists because a block tag works in
409 "both" directions. That is, a block tag doesn't just provide a hole to fill --
410 it also defines the content that fills the hole in the *parent*. If there were
411 two similarly-named :ttag:`block` tags in a template, that template's parent
412 wouldn't know which one of the blocks' content to use.
414 .. _next section: #automatic-html-escaping
415 .. _automatic-html-escaping:
417 Automatic HTML escaping
418 =======================
420 When generating HTML from templates, there's always a risk that a variable will
421 include characters that affect the resulting HTML. For example, consider this
426 At first, this seems like a harmless way to display a user's name, but consider
427 what would happen if the user entered his name as this::
429 <script>alert('hello')</script>
431 With this name value, the template would be rendered as::
433 Hello, <script>alert('hello')</script>
435 ...which means the browser would pop-up a JavaScript alert box!
437 Similarly, what if the name contained a ``'<'`` symbol, like this?
443 That would result in a rendered template like this::
447 ...which, in turn, would result in the remainder of the Web page being bolded!
449 Clearly, user-submitted data shouldn't be trusted blindly and inserted directly
450 into your Web pages, because a malicious user could use this kind of hole to
451 do potentially bad things. This type of security exploit is called a
452 `Cross Site Scripting`_ (XSS) attack.
454 To avoid this problem, you have two options:
456 * One, you can make sure to run each untrusted variable through the
457 :tfilter:`escape` filter (documented below), which converts potentially
458 harmful HTML characters to unharmful ones. This was the default solution
459 in Django for its first few years, but the problem is that it puts the
460 onus on *you*, the developer / template author, to ensure you're escaping
461 everything. It's easy to forget to escape data.
463 * Two, you can take advantage of Django's automatic HTML escaping. The
464 remainder of this section describes how auto-escaping works.
466 By default in Django, every template automatically escapes the output
467 of every variable tag. Specifically, these five characters are
470 * ``<`` is converted to ``<``
471 * ``>`` is converted to ``>``
472 * ``'`` (single quote) is converted to ``'``
473 * ``"`` (double quote) is converted to ``"``
474 * ``&`` is converted to ``&``
476 Again, we stress that this behavior is on by default. If you're using Django's
477 template system, you're protected.
479 .. _Cross Site Scripting: http://en.wikipedia.org/wiki/Cross-site_scripting
484 If you don't want data to be auto-escaped, on a per-site, per-template level or
485 per-variable level, you can turn it off in several ways.
487 Why would you want to turn it off? Because sometimes, template variables
488 contain data that you *intend* to be rendered as raw HTML, in which case you
489 don't want their contents to be escaped. For example, you might store a blob of
490 HTML in your database and want to embed that directly into your template. Or,
491 you might be using Django's template system to produce text that is *not* HTML
492 -- like an email message, for instance.
494 For individual variables
495 ~~~~~~~~~~~~~~~~~~~~~~~~
497 To disable auto-escaping for an individual variable, use the :tfilter:`safe`
500 This will be escaped: {{ data }}
501 This will not be escaped: {{ data|safe }}
503 Think of *safe* as shorthand for *safe from further escaping* or *can be
504 safely interpreted as HTML*. In this example, if ``data`` contains ``'<b>'``,
507 This will be escaped: <b>
508 This will not be escaped: <b>
513 To control auto-escaping for a template, wrap the template (or just a
514 particular section of the template) in the :ttag:`autoescape` tag, like so::
520 The :ttag:`autoescape` tag takes either ``on`` or ``off`` as its argument. At
521 times, you might want to force auto-escaping when it would otherwise be
522 disabled. Here is an example template::
524 Auto-escaping is on by default. Hello {{ name }}
527 This will not be auto-escaped: {{ data }}.
529 Nor this: {{ other_data }}
531 Auto-escaping applies again: {{ name }}
535 The auto-escaping tag passes its effect onto templates that extend the
536 current one as well as templates included via the :ttag:`include` tag,
537 just like all block tags. For example::
542 <h1>{% block title %}{% endblock %}</h1>
550 {% extends "base.html" %}
551 {% block title %}This & that{% endblock %}
552 {% block content %}{{ greeting }}{% endblock %}
554 Because auto-escaping is turned off in the base template, it will also be
555 turned off in the child template, resulting in the following rendered
556 HTML when the ``greeting`` variable contains the string ``<b>Hello!</b>``::
564 Generally, template authors don't need to worry about auto-escaping very much.
565 Developers on the Python side (people writing views and custom filters) need to
566 think about the cases in which data shouldn't be escaped, and mark data
567 appropriately, so things Just Work in the template.
569 If you're creating a template that might be used in situations where you're
570 not sure whether auto-escaping is enabled, then add an :tfilter:`escape` filter
571 to any variable that needs escaping. When auto-escaping is on, there's no
572 danger of the :tfilter:`escape` filter *double-escaping* data -- the
573 :tfilter:`escape` filter does not affect auto-escaped variables.
575 .. _string-literals-and-automatic-escaping:
577 String literals and automatic escaping
578 --------------------------------------
580 As we mentioned earlier, filter arguments can be strings::
582 {{ data|default:"This is a string literal." }}
584 All string literals are inserted **without** any automatic escaping into the
585 template -- they act as if they were all passed through the :tfilter:`safe`
586 filter. The reasoning behind this is that the template author is in control of
587 what goes into the string literal, so they can make sure the text is correctly
588 escaped when the template is written.
590 This means you would write ::
592 {{ data|default:"3 < 2" }}
596 {{ data|default:"3 < 2" }} <-- Bad! Don't do this.
598 This doesn't affect what happens to data coming from the variable itself.
599 The variable's contents are still automatically escaped, if necessary, because
600 they're beyond the control of the template author.
602 .. _template-accessing-methods:
604 Accessing method calls
605 ======================
607 Most method calls attached to objects are also available from within templates.
608 This means that templates have access to much more than just class attributes
609 (like field names) and variables passed in from views. For example, the Django
610 ORM provides the :ref:`"entry_set"<topics-db-queries-related>` syntax for
611 finding a collection of objects related on a foreign key. Therefore, given
612 a model called "comment" with a foreign key relationship to a model called
613 "task" you can loop through all comments attached to a given task like this::
615 {% for comment in task.comment_set.all %}
619 Similarly, :doc:`QuerySets</ref/models/querysets>` provide a ``count()`` method
620 to count the number of objects they contain. Therefore, you can obtain a count
621 of all comments related to the current task with::
623 {{ task.comment_set.all.count }}
625 And of course you can easily access methods you've explicitly defined on your
629 class Task(models.Model):
636 Because Django intentionally limits the amount of logic processing available
637 in the template language, it is not possible to pass arguments to method calls
638 accessed from within templates. Data should be calculated in views, then passed
639 to templates for display.
641 .. _loading-custom-template-libraries:
643 Custom tag and filter libraries
644 ===============================
646 Certain applications provide custom tag and filter libraries. To access them in
647 a template, use the :ttag:`load` tag::
651 {% comment_form for blogs.entries entry.id with is_public yes %}
653 In the above, the :ttag:`load` tag loads the ``comments`` tag library, which then
654 makes the ``comment_form`` tag available for use. Consult the documentation
655 area in your admin to find the list of custom libraries in your installation.
657 The :ttag:`load` tag can take multiple library names, separated by spaces.
660 {% load comments i18n %}
662 See :doc:`/howto/custom-template-tags` for information on writing your own custom
665 Custom libraries and template inheritance
666 -----------------------------------------
668 When you load a custom tag or filter library, the tags/filters are only made
669 available to the current template -- not any parent or child templates along
670 the template-inheritance path.
672 For example, if a template ``foo.html`` has ``{% load comments %}``, a child
673 template (e.g., one that has ``{% extends "foo.html" %}``) will *not* have
674 access to the comments template tags and filters. The child template is
675 responsible for its own ``{% load comments %}``.
677 This is a feature for the sake of maintainability and sanity.