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:

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 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:

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:

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.

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. For example:

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

Using Logical Operators

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

and operator

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

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 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:

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:

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.

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

Using Relational Operators

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

> operator

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

< operator

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

>= operator

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

<= operator

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

== operator

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

!= operator

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

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

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 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:

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.

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.

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

The output will be:

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

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

The output will be something like this:

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:

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:

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:

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

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:

Then the above for loop will print the following output:

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

Output:

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

Output:

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

Output:

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

Output:

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

Output:

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

4 thoughts on “Template tags in Django

  1. So I will preface that I’m only 7 pages into this tutorial. But I’ve looked at probably 30+ including the Django Official Documentation, Django Girls, and well…(see pic). As I’m trying to decide what I can really dive into to create a “project” with 3-4 applications it. And hopefully it in the short term is relatively fast (allows me to basically render HTML docs (with a templating, markdown, etc support) and also grow the app to where I would have a database for sports statistics retrieval/querying on the app.

    All that to say…this is the BEST tutorial I’ve seen yet. You’re mostly anonymous right now — so no idea where this website is going — and I find that somewhat humorous for someone SO GOOD at Django!

    But yeah…looking forward to the rest of the tutorial and looking forward to anything else you’re doing and if I can help publicize/support such good content.

    https://uploads.disquscdn.com/images/e465219cac43c438d81b91c68cd52d702ff8af879d7fb2e63ec64bfcaff410b9.png

Leave a Comment