As we’ve mentioned already, the template system ships with built-in tags and filters. The sections that follow provide a rundown of the most common tags and filters.
Tags
if/else – The {% if %} tag evaluates a variable, and if that variable is “true” (i.e., it exists, is not empty, and is not a false Boolean value), the system will display everything between {% if %} and {% endif %}, for example:
{% if today_is_weekend %} <p>Welcome to the weekend!</p> {% endif %} An {% else %} tag is optional:
{% if today_is_weekend %} <p>Welcome to the weekend!</p> {% else %} <p>Get back to work.</p> {% endif %}
Make sure to close each {% if %} with an {% endif %}, otherwise Django will throw a TemplateSyntaxError. The if tag may also take one or several {% elif %} clauses as well:
{% if athlete_list %} <p>Number of athletes: {{ athlete_list|length }}</p> {% elif athlete_in_locker_room_list %} <p>Athletes should be out of the locker room soon!</p> {% elif ... ... {% else %} <p>No athletes.</p> {% endif %}
The {% if %} tag accepts and, or, or not for testing multiple variables, or to negate a given variable. For example:
{% if athlete_list and coach_list %} <p>Both athletes and coaches are available.</p> {% endif %} {% if not athlete_list %} <p>There are no athletes.</p> {% endif %} {% if athlete_list or coach_list %} <p>There are some athletes or some coaches.</p> {% endif %} {% if not athlete_list or coach_list %} <p>There are no athletes or there are some coaches.</p> {% endif %} {% if athlete_list and not coach_list %} <p>There are some athletes and absolutely no coaches.</p> {% endif %}
Use of both and and or clauses within the same tag is allowed, with and having higher precedence than or e.g.:
{% if athlete_list and coach_list or cheerleader_list %}
will be interpreted like:
if (athlete_list and coach_list) or cheerleader_list
If you need parentheses to indicate precedence, you should use nested if tags. The use of parentheses for controlling order of operations is not supported. If you find yourself needing parentheses, consider performing logic outside the template and passing the result of that as a dedicated template variable. Or, just use nested {% if %} tags.
Multiple uses of the same logical operator are fine, but you can’t combine different operators. For example, this is valid:
{% if athlete_list or coach_list or parent_list or teacher_list %}
The {% if %} also accepts in / not in for testing whether a given value is or isn’t in the specified container, and is / is not for testing if two entities are the same object.
For example:
{% if "bc" in "abcdef" %} This appears since "bc" is a substring of "abcdef" {% endif %} {% if user not in users %} If users is a list, this will appear if user isn't an element of the list. {% endif %} {% if somevar is True %} This appears if and only if somevar is True. {% endif %} {% if somevar is not None %} This appears if somevar isn't None. {% endif %}
for – The {% for %} tag allows you to loop over each item in a sequence. As in Python’s for statement, the syntax is for X in Y, where Y is the sequence to loop over and X is the name of the variable to use for a particular cycle of the loop. Each time through the loop, the template system will render everything between {% for %} and {% endfor %}. For example, you could use the following to display a list of athletes given a variable athlete_list:
<ul> {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% endfor %} </ul>
Add reversed to the tag to loop over the list in reverse:
{% for athlete in athlete_list reversed %}...{% endfor %}
It’s possible to nest {% for %} tags:
{% for athlete in athlete_list %} <h1>{{ athlete.name }}</h1> <ul> {% for sport in athlete.sports_played %} <li>{{ sport }}</li> {% endfor %} </ul> {% endfor %}
If you need to loop over a list of lists, you can unpack the values in each sub list into individual variables. For example, if your context contains a list of (x,y) coordinates called points, you could use the following to output the list of points:
{% for x, y in points %} <p>There is a point at {{ x }},{{ y }}</p>{% endfor %}
This can also be useful if you need to access the items in a dictionary. For example, if your context contained a dictionary data, the following would display the keys and values of the dictionary:
{% for key, value in data.items %} {{ key }}: {{ value }} {% endfor %}
A common pattern is to check the size of the list before looping over it, and outputting some special text if the list is empty:
{% if athlete_list %} {% for athlete in athlete_list %} <p>{{ athlete.name }}</p> {% endfor %} {% else %} <p>There are no athletes. Only computer programmers.</p> {% endif %}
Because this pattern is so common, the for tag supports an optional {% empty %} clause that lets you define what to output if the list is empty. This example is equivalent to the previous one:
{% for athlete in athlete_list %} <p>{{ athlete.name }}</p> {% empty %} <p>There are no athletes. Only computer programmers.</p> {% endfor %}
There is no support for “breaking out” of a loop before the loop is finished. If you want to accomplish this, change the variable you’re looping over so that it includes only the values you want to loop over.
Similarly, there is no support for a “continue” statement that would instruct the loop processor to return immediately to the front of the loop.
Within each {% for %} loop, you get access to a template variable called forloop. This variable has a few attributes that give you information about the progress of the loop:
- forloop.counter is always set to an integer representing the number of times the loop has been entered. This is one-indexed, so the first time through the loop, forloop.counter will be set to 1. Here’s an example:
{% for item in todo_list %} <p>{{ forloop.counter }}: {{ item }}</p> {%endfor %}
- forloop.counter0 is like forloop.counter, except it’s zero-indexed. Its value will be set to 0 the first time through the loop.
- forloop.revcounter is always set to an integer representing the number of remaining items in the loop. The first time through the loop, forloop.revcounter will be set to the total number of items in the sequence you’re traversing. The last time through the loop, forloop.revcounter will be set to 1.
- revcounter0 is like forloop.revcounter, except it’s zero-indexed. The first time through the loop, forloop.revcounter0 will be set to the number of elements in the sequence minus 1. The last time through the loop, it will be set to 0.
- forloop.first is a Boolean value set to True if this is the first time through the loop. This is convenient for special-casing:
{% for object in objects %} {% if forloop.first %} <li class="first"> {% else %} <li> {% endif %} {{ object }}</li> {% endfor %}
- forloop.last is a Boolean value set to True if this is the last time through the loop. A common use for this is to put pipe characters between a list of links:
{% for link in links %} {{ link }}{% if not forloop.last %} | {% endif %} {% endfor %}
The above template code might output something like this:
Link1 | Link2 | Link3 | Link4
Another common use for this is to put a comma between words in a list:
{% for country in countries %} <table> {% for city in country.city_list %} <tr> <td>Country #{{ forloop.parentloop.counter }}</td> <td>City #{{ forloop.counter }}</td> <td>{{ city }}</td> </tr> {% endfor %} </table> {% endfor %}
- parentloop is a reference to the forloop object for the parent loop, in case of nested loops. Here’s an example:
{% for country in countries %} <table> {% for city in country.city_list %} <tr> <td>Country #{{ forloop.parentloop.counter }}</td> <td>City #{{ forloop.counter }}</td> <td>{{ city }}</td> </tr> {% endfor %} </table> {% endfor %}
The forloop variable is only available within loops. After the template parser has reached {% endfor %}, forloop disappears.
ifequal/ifnotequal – The {% ifequal %} / {% endifequal %} and {% ifnotequal %} / {% endifnotequal %} are obsolete ways to write {% if a == b %} / {% endif %} and {% if a != b %} / {% endif %} boolean operators. Reference to these obsolete tags have been removed from this Second Edition.
Comments – Just as in HTML or Python, the Django template language allows for comments. To designate a comment, use {# #}:
{# This is a comment #}
The comment will not be output when the template is rendered. Comments using this syntax cannot span multiple lines. This limitation improves template parsing performance.
In the following template, the rendered output will look exactly the same as the template (i.e., the comment tag will not be parsed as a comment):
This is a {# this is nota comment #}test.
If you want to use multi-line comments, use the {% comment %} template tag, like this:
{% comment %}This is amulti-line comment.{% endcomment %}
The comment tag may contain an optional note (e.g. to explain why that section of code has been commented out):
{% comment "This is the optional note" %} ...{% endcomment %} Comment tags cannot be nested.
Filters
As explained earlier in this chapter, template filters are simple ways of altering the value of variables before they’re displayed. Filters use a pipe character, like this:
{{ name|lower }}
This displays the value of the {{ name }} variable after being filtered through the lower filter, which converts text to lowercase. Filters can be chained – that is, they can be used in tandem such that the output of one filter is applied to the next.
Here’s an example that takes the first element in a list and converts it to uppercase:
{{ my_list|first|upper }}
Some filters take arguments. A filter argument comes after a colon and is always in double quotes. For example:
{{ bio|truncatewords:"30" }}
This displays the first 30 words of the bio variable. The following are a few of the most important filters.
- addslashes: Adds a backslash before any backslash, single quote, or double quote. This is useful for escaping strings. For example:{{ value|addslashes }}.
- date: Formats a date or datetime object according to a format string given in the parameter. For example: {{ pub_date|date:”F j, Y” }}Format strings are defined in Appendix E.
- length: Returns the length of the value. For a list, this returns the number of elements. For a string, this returns the number of characters. If the variable is undefined, length returns 0.