Template tags in Django

In the previous chapter, we have already introduced you to some of the basic template tags and filters. In this lesson, we will discuss some important built-in template tags in detail.

if tag #

The following is the syntax of the if tag:

Syntax:

{% if condition %}
    <p>Print this line</p>
{% endif %}

Here is how it works:

The if tag evaluates the value of the condition and if it is True (a variable in Python evaluates to True, if it contains a non empty value or non False Boolean value) then the template system will display everything between {% if %} and {% endif %}. For example:

{% if var %}
    <p>Print this para</p>
{% endif %}

If the value of var is 10 then <p>Print this para</p> will be printed. On the other hand, if the value of p is [] (an empty array) or {} (an empty dictionary) or 0 (numerical zero) or False (a Boolean false) then nothing will be printed.

It is important to close each {% if %} with a corresponding {% endif %}. Otherwise, Django will throw TemplateSyntaxError exception.

You can also add an optional {% else %} tag to the if tag like this:

{% if var %}
    <p>Print this para</p>
{% else %}
    <p>Else print the other para</p>
{% endif %}

Here is how it works:

First, the value of var is evaluated, if it is True then <p>Print this para</p> will be printed. Otherwise, <p>Else print the other para</p> will be printed.

You can also add one or more {% elif %} clauses to add some more conditions. For example:

{% if count < 10 %}
    <p>Print this para</p>
{% elif count < 20 %}    
    <p>Otherwise print this</p>
{% elif count < 30 %}
    <p>Let's try this</p>
{% else %}
    <p>Okay everything failed print this now</p>
{% endif %}

Here is how it works:

Each variable or condition is evaluated one by one. When a condition or variable is evaluated to True then the code only in that block is executed and evaluation of all the other conditions are skipped.

Comments #

Django template uses the following syntax to write comments.

{# This is a comment #}

The comment you write using this syntax will not be rendered in the HTML source code. Further, you can't expand this comment to multiple lines.

{# This is
not a comment #}

If you want to write comments in multiple lines using the following syntax:

{% comment %}
This is a comment expanding to
multiple lines.
{% endcomment %}

Using Logical Operators #

You can also use logical and, or and not operators to test multiple conditions. For example:

and operator #

{% if palindrome and even %}
    <p>Number is palindrome and even</p>
{% endif %}

This will print <p>Number is palindrome and even</p> only when both variables are evaluated to True. Otherwise, nothing would be printed at all.

not operator #

{% if not post_list %}
    <p>There are no blog post</p>
{% endif %}

The not operator negates the value of the condition. So the above code would print <p>There are no blog posts</p> only when post_list is False. In other words, if there are no blog posts print <p>There are no blog posts</p>.

or operator #

{% if post_list or page_list %}
    <p>The site has some blog post or pages</p>
{% endif %}

If anyone of the two variables evaluates to True then <p>The site has some blog post or pages</p> would be printed. Otherwise, nothing would be printed at all.

Here are some more examples:

{% if not post_list or page_list %}
    <p>The site has no posts or it has some pages</p>
{% endif %}

It is important to note here that not negates post_list only not the page_list. So the string <p>The site has not posts or it has some pages</p> will only get printed when either the site has no posts (i.e post_list empty) or it has some pages (page_list is not empty).

You can also use and and or operator within the same tag. The important thing to remember is that the precedence of and is higher than that of or operator. For example:

{% if post_list and page_list or author_list %}
    <p>The site has either both posts and pages or only author</p>
{% endif %}

Here is how it works:

If the site either has posts and pages or authors only then the string <p>The site has either both posts and pages or only author</p> would be printed.

Another important thing I want to clarify is that, don't be tempted to use parentheses to group expression in the if tag. It is invalid syntax and would throw TemplateSyntaxError exception.

{######## ERROR - DON'T DO IT ########}

{% if (post_list and page_list) or author_list %}
    <p>The site has either both posts and pages or only author</p>
{% endif %}

You can also nest one if tag inside another if tag. For example:

{% if num < 10 %}
    {% if num > 5 %}
        <p>The num is greater than 5 but less than 10</p>
    {% endif %}    
{% endif %}

Using Relation Operators #

You can also use relation operators >, <, >=, <=, != , == with the template tags.

> operator #

{% if num > 10 %}
    <p>The num is greater than 10</p>
{% endif %}

It will print <p>The num is greater than 10</p> if num is greater than 10.

< operator #

{% if num < 10 %}
    <p>The num is lesser than 10</p>
{% endif %}

It will prints <p>The num is lesser than 10</p> if num is smaller than 10.

>= operator #

{% if num >= 10 %}
    <p>The num is greater than or equal to 10</p>
{% endif %}

It will print <p>The num is greater than or equal to 10</p> if num is greater than or equal to 10.

<= operator #

{% if num <= 10 %}
    <p>The num is lesser than or equal to 10</p>
{% endif %}

It will print <p>The num is lesser than or equal to 10</p> if num is smaller than or equal to 10.

== operator #

{% if num == 10 %}
    <p>The num is equal to 10</p>
{% endif %}

It will print <p>The number is equal to 10</p> if num is equal to 10.

!= operator #

{% if num != 10 %}
    <p>The num is not equal to 10</p>
{% endif %}

It will print <p>The num is not equal to 10</p> if num is not equal to 10.

in, not in and is operator #

in operator #

{% if number in list %}
    <p>Yes the number is in the list</p>
{% endif %}

The in operator will check whether the number is in the list or not. If it is, then the text <p>Yes number is in the list</p> will be printed.

not in operator #

{% if number not in list %}
    <p>Yes the number is not in the list</p>
{% endif %}

The not in operator will check whether the number is in the list or not. If it is not, then the text <p>Yes the number is not in the list</p> will be printed.

is operator #

The is operator in Python is used to compare two objects. If two objects are same then the is operator returns True. Otherwise False.

{% if obj is user %}
    <p>Yes obj is same as user</p>
{% endif %}

If object pointed to by variable obj is same as that of variable user then the text <p>Yes obj is same as user</p> would be printed.

for tag #

A for tag allows us to use to loop through a sequence. We can use for tag to iterate over the contents of list, tuples, dictionary etc. Here is the syntax of the for tag:

{% for i in list %}
    <p>The value of i is {{ i }}</p>
{% endfor %}

Here is how it works:

When the loop begins the first value from the list is assigned to the variable i. Then the template engine will render everything between {% for %} and {% endfor %}. This process keeps repeating until there are no more elements left to iterate in the list.

To print a list in the reverse order add reversed keyword after the list as follows.

{% for i in list reversed %}
    <p>The value of i is {{ i }}</p>
{% endfor %}

Sometimes in your Django journey, you have to work with list of list. To access the list of list unpack elements of sublist into individual variables. For example, let's say we have the following list in our context.

list = [ ["uno", "one"], ["dos", "two"], ["tres", "three"], ["cuatro", "four"] ]

To loop over a list of list inside the template do this:

{% for x, y in list %}
    <p>{{ x }} : {{ y }}</p>
{% endfor %}

The output will be:

uno : one
dos : two
tres : three
cuatro : four

Similarly, we can access elements of a dictionary. Let's say our context variable contains a dictionary named dict.

dict = { 'uno': 'one', 'dos': 'two', 'tres': 'three', 'cuatro': 'four' }

To access this dictionary inside the template use the following code:

{% for k, v in dict.items %}
    <p>{{ k }} : {{ v }}</p>
{% endfor %}

The output will be something like this:

cuatro : four
uno : one
tres : three
dos : two

The important thing to remember here is that elements in a dictionary are stored in no particular order. So the above output may differ.

for empty tag #

Suppose we have a context variable called post_list which is a list of post objects. Our job is to print a list of all blog posts. We can do so using a for tag as follows:

{% for post in post_list %}
    <h2>{{ post.title }}</h2>
{% endfor %}

There is one problem though we haven't checked whether any blog posts exists or not. We can easily test whether post_list is empty or not by using an if tag as follows:

{% if post_list %}
    {% for post in post_list %}
        <h2>{{ post.title }}</h2>
    {% endfor %}
{% else %}
    No post published yet.
{% endif %}

This kind of pattern is so common that Django provides a nice shortcut to it. The for tag can take an additional {% empty %} tag. This tag let you define what to output in the case if list is empty. For example:

{% for post in post_list %}
    <h2>{{ post.title }}</h2>
{% empty %}
    No post published yet.        
{% endfor %}

Just like nested if tags we can have nested for tags.

{% for post in post_list %}
    <p>{{ post.content }}</p>
    <p>
        <ul>
            {% for tag in post.tags %}
            <li>{{ tag }}</li>
            {% endfor %}            
        </ul>
    </p>
{% endfor %}

The for tag provides a special variable called forloop. The forloop variable has few attributes you can use to track the progress of the loop.

forloop.counter - It returns a number indicating the current iteration of the loop. It starts with 1. For example, let's say our context contains a list named list defined as follows:

list = [11,12,13]
{% for i in list %}
    <p>{{ forloop.counter }} Iteration - {{ i }}</p>
{% endfor %}

Then the above for loop will print the following output:

1 Iteration - 11
2 Iteration - 12
3 Iteration - 13

forloop.counter0 - Works same as forloop.counter but begins with 0 instead of 1.

{% for i in list %}
    <p>{{ forloop.counter0 }} Iteration - {{ i }}</p>
{% endfor %}

Output:

0 Iteration - 11
1 Iteration - 12
2 Iteration - 13

forloop.revcounter - It returns the number of iteration from the end of the loop.

{% for i in list %}
    <p>{{ forloop.revcounter }} Iteration - {{ i }}</p>
{% endfor %}

Output:

3 Iteration - 11
2 Iteration - 12
1 Iteration - 13

forloop.revcounter0 - Same as forloop.revcounter but it is 0 indexed.

{% for i in list %}
    <p>{{ forloop.revcounter0 }} Iteration - {{ i }}</p>
{% endfor %}

Output:

2 Iteration - 11
1 Iteration - 12
0 Iteration - 13

forloop.first - It returns a Boolean True if the current iteration is the first iteration. Otherwise False.

{% for i in list %}
    <p>{{ forloop.first }} Iteration - {{ i }}</p>
{% endfor %}

Output:

True Iteration - 11
False Iteration - 12
False Iteration - 13

forloop.last - It returns a Boolean True if the current iteration is the last iteration. Otherwise False.

{% for i in list %}
    <p>{{ forloop.last }} Iteration - {{ i }}</p>
{% endfor %}

Output:

False Iteration - 11
False Iteration - 12
True Iteration - 13

forloop.parentloop - It is used in the nested for loop to refer to the forloop variable in the parent for loop. For example:

{% for i in list %}
    <table>
    {% for j in i %}
        <tr>
            <td>{{ forloop.parentloop.counter }} - {{ forloop.counter }} - {{ i }}</td>
        </tr>
    {% endfor %}
    </table>
{% endfor %}