The Django template language

This document explains the language syntax of the Django template system. Ifyou're looking for a more technical perspective on how it works and how toextend it, see The Django template language: for Python programmers.

Django's template language is designed to strike a balance between power andease. It's designed to feel comfortable to those used to working with HTML. Ifyou have any exposure to other text-based template languages, such as Smartyor Jinja2, you should feel right at home with Django's templates.

Philosophy

If you have a background in programming, or if you're used to languageswhich mix programming code directly into HTML, you'll want to bear inmind that the Django template system is not simply Python embedded intoHTML. This is by design: the template system is meant to expresspresentation, not program logic.

The Django template system provides tags which function similarly to someprogramming constructs — an if tag for boolean tests, a fortag for looping, etc. — but these are not simply executed as thecorresponding Python code, and the template system will not executearbitrary Python expressions. Only the tags, filters and syntax listed beloware supported by default (although you can add your own extensions to the template language as needed).

Templates

A template is simply a text file. It can generate any text-based format (HTML,XML, CSV, etc.).

A template contains variables, which get replaced with values when thetemplate is evaluated, and tags, which control the logic of the template.

Below is a minimal template that illustrates a few basics. Each element will beexplained later in this document.

  1. {% extends "base_generic.html" %}
  2.  
  3. {% block title %}{{ section.title }}{% endblock %}
  4.  
  5. {% block content %}
  6. <h1>{{ section.title }}</h1>
  7.  
  8. {% for story in story_list %}
  9. <h2>
  10. <a href="{{ story.get_absolute_url }}">
  11. {{ story.headline|upper }}
  12. </a>
  13. </h2>
  14. <p>{{ story.tease|truncatewords:"100" }}</p>
  15. {% endfor %}
  16. {% endblock %}

Philosophy

Why use a text-based template instead of an XML-based one (like Zope'sTAL)? We wanted Django's template language to be usable for more thanjust XML/HTML templates. At World Online, we use it for emails,JavaScript and CSV. You can use the template language for any text-basedformat.

Oh, and one more thing: making humans edit XML is sadistic!

Variables

Variables look like this: {{ variable }}. When the template engineencounters a variable, it evaluates that variable and replaces it with theresult. Variable names consist of any combination of alphanumeric charactersand the underscore (""). The dot (".") also appears in variablesections, although that has a special meaning, as indicated below.Importantly, _you cannot have spaces or punctuation characters in variablenames.

Use a dot (.) to access attributes of a variable.

Behind the scenes

Technically, when the template system encounters a dot, it tries thefollowing lookups, in this order:

  • Dictionary lookup
  • Attribute or method lookup
  • Numeric index lookupIf the resulting value is callable, it is called with no arguments. Theresult of the call becomes the template value.

This lookup order can cause some unexpected behavior with objects thatoverride dictionary lookup. For example, consider the following code snippetthat attempts to loop over a collections.defaultdict:

  1. {% for k, v in defaultdict.items %}
  2. Do something with k and v here...
  3. {% endfor %}

Because dictionary lookup happens first, that behavior kicks in and providesa default value instead of using the intended .items() method. In thiscase, consider converting to a dictionary first.

In the above example, {{ section.title }} will be replaced with thetitle attribute of the section object.

If you use a variable that doesn't exist, the template system will insert thevalue of the string_if_invalid option, which is set to '' (the emptystring) by default.

Note that "bar" in a template expression like {{ foo.bar }} will beinterpreted as a literal string and not using the value of the variable "bar",if one exists in the template context.

Filters

You can modify variables for display by using filters.

Filters look like this: {{ name|lower }}. This displays the value of the{{ name }} variable after being filtered through the lowerfilter, which converts text to lowercase. Use a pipe (|) to apply a filter.

Filters can be "chained." The output of one filter is applied to the next.{{ text|escape|linebreaks }} is a common idiom for escaping text contents,then converting line breaks to <p> tags.

Some filters take arguments. A filter argument looks like this: {{bio|truncatewords:30 }}. This will display the first 30 words of the biovariable.

Filter arguments that contain spaces must be quoted; for example, to join alist with commas and spaces you'd use {{ list|join:", " }}.

Django provides about sixty built-in template filters. You can read all aboutthem in the built-in filter reference.To give you a taste of what's available, here are some of the more commonlyused template filters:

  • default
  • If a variable is false or empty, use given default. Otherwise, use thevalue of the variable. For example:
  1. {{ value|default:"nothing" }}

If value isn't provided or is empty, the above will display"nothing".

  • length
  • Returns the length of the value. This works for both strings and lists.For example:
  1. {{ value|length }}

If value is ['a', 'b', 'c', 'd'], the output will be 4.

  • filesizeformat
  • Formats the value like a "human-readable" file size (i.e. '13 KB','4.1 MB', '102 bytes', etc.). For example:
  1. {{ value|filesizeformat }}

If value is 123456789, the output would be 117.7 MB.

Again, these are just a few examples; see the built-in filter reference for the complete list.

You can also create your own custom template filters; seeCustom template tags and filters.

See also

Django's admin interface can include a complete reference of all templatetags and filters available for a given site. SeeThe Django admin documentation generator.

Tags

Tags look like this: {% tag %}. Tags are more complex than variables: Somecreate text in the output, some control flow by performing loops or logic, andsome load external information into the template to be used by later variables.

Some tags require beginning and ending tags (i.e. {% tag %} … tag contents… {% endtag %}).

Django ships with about two dozen built-in template tags. You can read all aboutthem in the built-in tag reference. To giveyou a taste of what's available, here are some of the more commonly usedtags:

  • for
  • Loop over each item in an array. For example, to display a list of athletesprovided in athlete_list:
  1. <ul>
  2. {% for athlete in athlete_list %}
  3. <li>{{ athlete.name }}</li>
  4. {% endfor %}
  5. </ul>
  • if, elif, and else
  • Evaluates a variable, and if that variable is "true" the contents of theblock are displayed:
  1. {% if athlete_list %}
  2. Number of athletes: {{ athlete_list|length }}
  3. {% elif athlete_in_locker_room_list %}
  4. Athletes should be out of the locker room soon!
  5. {% else %}
  6. No athletes.
  7. {% endif %}

In the above, if athlete_list is not empty, the number of athleteswill be displayed by the {{ athlete_list|length }} variable. Otherwise,if athlete_in_locker_room_list is not empty, the message "Athletesshould be out…" will be displayed. If both lists are empty,"No athletes." will be displayed.

You can also use filters and various operators in the if tag:

  1. {% if athlete_list|length > 1 %}
  2. Team: {% for athlete in athlete_list %} ... {% endfor %}
  3. {% else %}
  4. Athlete: {{ athlete_list.0.name }}
  5. {% endif %}

While the above example works, be aware that most template filters returnstrings, so mathematical comparisons using filters will generally not workas you expect. length is an exception.

You can also create your own custom template tags; seeCustom template tags and filters.

See also

Django's admin interface can include a complete reference of all templatetags and filters available for a given site. SeeThe Django admin documentation generator.

Comments

To comment-out part of a line in a template, use the comment syntax: {# #}.

For example, this template would render as 'hello':

  1. {# greeting #}hello

A comment can contain any template code, invalid or not. For example:

  1. {# {% if foo %}bar{% else %} #}

This syntax can only be used for single-line comments (no newlines are permittedbetween the {# and #} delimiters). If you need to comment out amultiline portion of the template, see the comment tag.

Template inheritance

The most powerful — and thus the most complex — part of Django's templateengine is template inheritance. Template inheritance allows you to build a base"skeleton" template that contains all the common elements of your site anddefines blocks that child templates can override.

It's easiest to understand template inheritance by starting with an example:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <link rel="stylesheet" href="style.css" />
  5. <title>{% block title %}My amazing site{% endblock %}</title>
  6. </head>
  7.  
  8. <body>
  9. <div id="sidebar">
  10. {% block sidebar %}
  11. <ul>
  12. <li><a href="/">Home</a></li>
  13. <li><a href="/blog/">Blog</a></li>
  14. </ul>
  15. {% endblock %}
  16. </div>
  17.  
  18. <div id="content">
  19. {% block content %}{% endblock %}
  20. </div>
  21. </body>
  22. </html>

This template, which we'll call base.html, defines a simple HTML skeletondocument that you might use for a simple two-column page. It's the job of"child" templates to fill the empty blocks with content.

In this example, the block tag defines three blocks that childtemplates can fill in. All the block tag does is to tell the templateengine that a child template may override those portions of the template.

A child template might look like this:

  1. {% extends "base.html" %}
  2.  
  3. {% block title %}My amazing blog{% endblock %}
  4.  
  5. {% block content %}
  6. {% for entry in blog_entries %}
  7. <h2>{{ entry.title }}</h2>
  8. <p>{{ entry.body }}</p>
  9. {% endfor %}
  10. {% endblock %}

The extends tag is the key here. It tells the template engine thatthis template "extends" another template. When the template system evaluatesthis template, first it locates the parent — in this case, "base.html".

At that point, the template engine will notice the three block tagsin base.html and replace those blocks with the contents of the childtemplate. Depending on the value of blog_entries, the output might looklike:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <link rel="stylesheet" href="style.css" />
  5. <title>My amazing blog</title>
  6. </head>
  7.  
  8. <body>
  9. <div id="sidebar">
  10. <ul>
  11. <li><a href="/">Home</a></li>
  12. <li><a href="/blog/">Blog</a></li>
  13. </ul>
  14. </div>
  15.  
  16. <div id="content">
  17. <h2>Entry one</h2>
  18. <p>This is my first entry.</p>
  19.  
  20. <h2>Entry two</h2>
  21. <p>This is my second entry.</p>
  22. </div>
  23. </body>
  24. </html>

Note that since the child template didn't define the sidebar block, thevalue from the parent template is used instead. Content within a {% block %}tag in a parent template is always used as a fallback.

You can use as many levels of inheritance as needed. One common way of usinginheritance is the following three-level approach:

  • Create a base.html template that holds the main look-and-feel of yoursite.
  • Create a base_SECTIONNAME.html template for each "section" of yoursite. For example, base_news.html, base_sports.html. Thesetemplates all extend base.html and include section-specificstyles/design.
  • Create individual templates for each type of page, such as a newsarticle or blog entry. These templates extend the appropriate sectiontemplate.This approach maximizes code reuse and makes it easy to add items to sharedcontent areas, such as section-wide navigation.

Here are some tips for working with inheritance:

  • If you use {% extends %} in a template, it must be the first templatetag in that template. Template inheritance won't work, otherwise.

  • More {% block %} tags in your base templates are better. Remember,child templates don't have to define all parent blocks, so you can fillin reasonable defaults in a number of blocks, then only define the onesyou need later. It's better to have more hooks than fewer hooks.

  • If you find yourself duplicating content in a number of templates, itprobably means you should move that content to a {% block %} in aparent template.

  • If you need to get the content of the block from the parent template,the {{ block.super }} variable will do the trick. This is usefulif you want to add to the contents of a parent block instead ofcompletely overriding it. Data inserted using {{ block.super }} willnot be automatically escaped (see the next section), since it wasalready escaped, if necessary, in the parent template.

  • Variables created outside of a {% block %} using the templatetag as syntax can't be used inside the block. For example, this templatedoesn't render anything:

  1. {% trans "Title" as title %}
  2. {% block content %}{{ title }}{% endblock %}
  • For extra readability, you can optionally give a name to your{% endblock %} tag. For example:
  1. {% block content %}
  2. ...
  3. {% endblock content %}

In larger templates, this technique helps you see which {% block %}tags are being closed.

Finally, note that you can't define multiple block tags with the samename in the same template. This limitation exists because a block tag works in"both" directions. That is, a block tag doesn't just provide a hole to fill —it also defines the content that fills the hole in the parent. If there weretwo similarly-named block tags in a template, that template's parentwouldn't know which one of the blocks' content to use.

Automatic HTML escaping

When generating HTML from templates, there's always a risk that a variable willinclude characters that affect the resulting HTML. For example, consider thistemplate fragment:

  1. Hello, {{ name }}

At first, this seems like a harmless way to display a user's name, but considerwhat would happen if the user entered their name as this:

  1. <script>alert('hello')</script>

With this name value, the template would be rendered as:

  1. Hello, <script>alert('hello')</script>

…which means the browser would pop-up a JavaScript alert box!

Similarly, what if the name contained a '<' symbol, like this?

  1. <b>username

That would result in a rendered template like this:

  1. Hello, <b>username

…which, in turn, would result in the remainder of the Web page being bolded!

Clearly, user-submitted data shouldn't be trusted blindly and inserted directlyinto your Web pages, because a malicious user could use this kind of hole todo potentially bad things. This type of security exploit is called aCross Site Scripting (XSS) attack.

To avoid this problem, you have two options:

  • One, you can make sure to run each untrusted variable through theescape filter (documented below), which converts potentiallyharmful HTML characters to unharmful ones. This was the default solutionin Django for its first few years, but the problem is that it puts theonus on you, the developer / template author, to ensure you're escapingeverything. It's easy to forget to escape data.
  • Two, you can take advantage of Django's automatic HTML escaping. Theremainder of this section describes how auto-escaping works.By default in Django, every template automatically escapes the outputof every variable tag. Specifically, these five characters areescaped:

  • < is converted to &lt;

  • > is converted to &gt;
  • ' (single quote) is converted to &#39;
  • " (double quote) is converted to &quot;
  • & is converted to &amp;Again, we stress that this behavior is on by default. If you're using Django'stemplate system, you're protected.

How to turn it off

If you don't want data to be auto-escaped, on a per-site, per-template level orper-variable level, you can turn it off in several ways.

Why would you want to turn it off? Because sometimes, template variablescontain data that you intend to be rendered as raw HTML, in which case youdon't want their contents to be escaped. For example, you might store a blob ofHTML in your database and want to embed that directly into your template. Or,you might be using Django's template system to produce text that is not HTML— like an email message, for instance.

For individual variables

To disable auto-escaping for an individual variable, use the safefilter:

  1. This will be escaped: {{ data }}
  2. This will not be escaped: {{ data|safe }}

Think of safe as shorthand for safe from further escaping or can besafely interpreted as HTML. In this example, if data contains '<b>',the output will be:

  1. This will be escaped: &lt;b&gt;
  2. This will not be escaped: <b>

For template blocks

To control auto-escaping for a template, wrap the template (or just aparticular section of the template) in the autoescape tag, like so:

  1. {% autoescape off %}
  2. Hello {{ name }}
  3. {% endautoescape %}

The autoescape tag takes either on or off as its argument. Attimes, you might want to force auto-escaping when it would otherwise bedisabled. Here is an example template:

  1. Auto-escaping is on by default. Hello {{ name }}
  2.  
  3. {% autoescape off %}
  4. This will not be auto-escaped: {{ data }}.
  5.  
  6. Nor this: {{ other_data }}
  7. {% autoescape on %}
  8. Auto-escaping applies again: {{ name }}
  9. {% endautoescape %}
  10. {% endautoescape %}

The auto-escaping tag passes its effect onto templates that extend thecurrent one as well as templates included via the include tag,just like all block tags. For example:

base.html

  1. {% autoescape off %}
  2. <h1>{% block title %}{% endblock %}</h1>
  3. {% block content %}
  4. {% endblock %}
  5. {% endautoescape %}

child.html

  1. {% extends "base.html" %}
  2. {% block title %}This &amp; that{% endblock %}
  3. {% block content %}{{ greeting }}{% endblock %}

Because auto-escaping is turned off in the base template, it will also beturned off in the child template, resulting in the following renderedHTML when the greeting variable contains the string <b>Hello!</b>:

  1. <h1>This &amp; that</h1>
  2. <b>Hello!</b>

Notes

Generally, template authors don't need to worry about auto-escaping very much.Developers on the Python side (people writing views and custom filters) need tothink about the cases in which data shouldn't be escaped, and mark dataappropriately, so things Just Work in the template.

If you're creating a template that might be used in situations where you'renot sure whether auto-escaping is enabled, then add an escape filterto any variable that needs escaping. When auto-escaping is on, there's nodanger of the escape filter double-escaping data — theescape filter does not affect auto-escaped variables.

String literals and automatic escaping

As we mentioned earlier, filter arguments can be strings:

  1. {{ data|default:"This is a string literal." }}

All string literals are inserted without any automatic escaping into thetemplate — they act as if they were all passed through the safefilter. The reasoning behind this is that the template author is in control ofwhat goes into the string literal, so they can make sure the text is correctlyescaped when the template is written.

This means you would write

  1. {{ data|default:"3 &lt; 2" }}

…rather than:

  1. {{ data|default:"3 < 2" }} {# Bad! Don't do this. #}

This doesn't affect what happens to data coming from the variable itself.The variable's contents are still automatically escaped, if necessary, becausethey're beyond the control of the template author.

Accessing method calls

Most method calls attached to objects are also available from within templates.This means that templates have access to much more than just class attributes(like field names) and variables passed in from views. For example, the DjangoORM provides the "entry_set" syntax forfinding a collection of objects related on a foreign key. Therefore, givena model called "comment" with a foreign key relationship to a model called"task" you can loop through all comments attached to a given task like this:

  1. {% for comment in task.comment_set.all %}
  2. {{ comment }}
  3. {% endfor %}

Similarly, QuerySets provide a count() methodto count the number of objects they contain. Therefore, you can obtain a countof all comments related to the current task with:

  1. {{ task.comment_set.all.count }}

And of course you can easily access methods you've explicitly defined on yourown models:

models.py

  1. class Task(models.Model):
  2. def foo(self):
  3. return "bar"

template.html

  1. {{ task.foo }}

Because Django intentionally limits the amount of logic processing availablein the template language, it is not possible to pass arguments to method callsaccessed from within templates. Data should be calculated in views, then passedto templates for display.

Custom tag and filter libraries

Certain applications provide custom tag and filter libraries. To access them ina template, ensure the application is in INSTALLED_APPS (we'd add'django.contrib.humanize' for this example), and then use the loadtag in a template:

  1. {% load humanize %}
  2.  
  3. {{ 45000|intcomma }}

In the above, the load tag loads the humanize tag library, which thenmakes the intcomma filter available for use. If you've enableddjango.contrib.admindocs, you can consult the documentation area in youradmin to find the list of custom libraries in your installation.

The load tag can take multiple library names, separated by spaces.Example:

  1. {% load humanize i18n %}

See Custom template tags and filters for information on writing your own customtemplate libraries.

Custom libraries and template inheritance

When you load a custom tag or filter library, the tags/filters are only madeavailable to the current template — not any parent or child templates alongthe template-inheritance path.

For example, if a template foo.html has {% load humanize %}, a childtemplate (e.g., one that has {% extends "foo.html" %}) will not haveaccess to the humanize template tags and filters. The child template isresponsible for its own {% load humanize %}.

This is a feature for the sake of maintainability and sanity.

See also