Table of contents
1.
Introduction
2.
Django Templates
3.
Tags in Django Templates
4.
Commonly used Tags in Django Templates
4.1.
Autoescape :
4.2.
Comment :
4.3.
Cycle and for loop: 
4.4.
Extends :
4.5.
If :
4.6.
For …empty loop :
4.7.
Boolean Operators:
4.8.
Include :
4.9.
Lorem :
5.
Frequently Asked Questions
6.
Key Takeaways
Last Updated: Mar 27, 2024

Tags in Django Templates

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Django is one of Python's most popular, trusted, and reliable web development frameworks. With Django, we can quickly create web applications without worrying about installation or dependency problems that we usually find with other frameworks.

Django provides convenience to rendering data in a template. Django templates allow the passing of data from view to template and also provide some limited features of programming such as variables, for loops, etc. Django Template Tags are Python functions that accept one or more values, optional arguments, process those values and return a value to be displayed on the page.

In this article, we will learn about tags in Django Templates. So, let's get started.

Django Templates

As we know, HTML is a static language and can't interpret with the python code as it is a dynamic language, so Django templates act as a bridge between these two and help form dynamic HTML pages.

Django Templates also contain static parts as they are written in the desired HTMLCSS, and Javascript output. With the help of this, the pages can be rendered quickly and efficiently, and the process becomes easy.

Refer to Django Template to learn about Templates in Django in detail.

This article will focus on Tags in Django Templates in detail.

Tags in Django Templates

Tags in Django Templates look like this: {% tag %}. Tags are more complex than variables: Tags can create text in the output, control structure with loops or logic, and load external information into the Django template to be used by later variables.

In Django templates, tags provide arbitrary logic during the rendering process. For example, a tag can output text, serve as a control structure with the help of loops or logic e.g. a ‘for’ loop or an ‘if’ statement. A tag can also grab information from the database.

Given below is an example of the usage of tags in Django templates. The code will print “Hello, {{ user.username }}.”  only if user.is_authenticated is true. {% csrf_token %}, {% if user.is_authenticated %} and {%endif %} are tags while {{ user.username}} is a variable.

{% csrf_token %}  
 
{% if user.is_authenticated %}  
    Hello, {{ user.username }}.  
{% endif %} 
You can also try this code with Online Python Compiler
Run Code

 

Let’s take our user as logged in with a username of ‘Naman’, then the above template will render to:

Hello, Naman. 

 

Commonly used Tags in Django Templates

Autoescape :

This tag controls the current auto-escaping behaviour. autoescape tag accepts either on or off as the argument and that determines whether auto-escaping is in effect or not. The block ends with an endautoescape ending tag.

When autoescaping is on, which is the default, the HTML tags in variables will be escaped using HTML entities before placing the result into the output (but after any filters have been applied). 

Example Usage autoescape on:

variable_item = '<p>You are <em>intelligent</em> and smart!</p>'
 
{% autoescape %}  
    { variable_item }  
{% endautoescape %} 
You can also try this code with Online Python Compiler
Run Code

    

Output:


 

Example usage autoescape off:

variable_item = '<p>You are <em>intelligent</em> and smart!</p>'
 
{% autoescape off %}  
    { variable_item }  
{% endautoescape %} 
You can also try this code with Online Python Compiler
Run Code

 

Output:

Comment :

We use Comment tags to comment out code to prevent interpretation of template tags or variables and prevent the content from being delivered. Any content between {% comment %} and {% endcomment %} is ignored by the Django template. Any optional content may be inserted in {% comment <content> %}.

Example Usage:

variable_item = '<p>You are <em>intelligent</em> and smart!</p>'
 
{% comment “should we remove this?” %}  
    { variable_item }  
{% endcomment %}     
You can also try this code with Online Python Compiler
Run Code

 

The above code will comment out everything between {% comment %} and {% endcomment %}. The comment here added is useful for fellow developers.

Cycle and for loop: 

The cycle tag iterates through all of its given arrays one by one and produces an argument every time with the iterated item. It produces the first argument on the first iteration, the second argument on the second iteration, the third argument on the third iteration, etc. Once alliteration is completed the tag cycles to the first iteration again and produces the first argument again.

The {% for %} tag iterates over every item in the array. We can access the item using a context variable.

Example usage: 

seat_arrangement = ['Naman', 'Nisha', 'Rahul', 'Snehal', 'Joy']

<ol> 
{% for all student in seat_arrangement %}  
    <li class="{% cycle 'row1' 'row2' %}">{{ student }}</li>  
{% endfor %} 
</ol>
You can also try this code with Online Python Compiler
Run Code

 

The above code iterates through seat_arrangement using {% for %} tag. In every iteration, the {% cycle %} tag cycles through ‘row1’ and ‘row2’ to produce a list of sitting arrangements of students.

Output:

<ol>

  <li class="row1">Naman</li>

  <li class="row2">Nisha</li>

  <li class="row1">Rahul</li>

  <li class="row2">Snehal</li>

  <li class="row1">Joy</li>

</ol>

 

Extends :

This tag is used for the inheritance of Django templates. We don’t need to repeat the same code again and again. With extends, we can inherit Django templates as well as Django variables.

Example usage: 

{% extends "./header.html" %}
You can also try this code with Online Python Compiler
Run Code

 

In the above code with the extent tag, we have inherited the header.html template in our new template.

If :

The {% if %} tag in the Django template is the conditional tag, and it works just like it does in Python.

Example Usage:

a= 5
b= 6
c= 5
{% if a == b %}
  <p>a is equal to b</p>
{% elif a == c %}
  <p>a is equal to c</p>
{% else %}
  <p>a is not equal to c and b</p>
{% endif %}
You can also try this code with Online Python Compiler
Run Code

 

The above code checks if a is equal to b or c using Django operators and prints the answer after rendering the template. The output of the following code is:

Output:

a is equal to c

 

For …empty loop :

The {% for %} tag can take an optional {% empty %} clause whose text is displayed if the given array is empty or could not be found:

Example usage: 

seat_arrangement = []

<ol> 
{% for all student in seat_arrangement %}  
    <li class="{% cycle 'row1' 'row2' %}">{{ student }}</li>
{% empty %}
    <li>Sorry, no students in this list.</li>  
{% endfor %} 
</ol>
You can also try this code with Online Python Compiler
Run Code

 

Since the seat_arrangement list is empty, it will display the text under the {% empty %} clause.

Output:

<ol>

  <li>Sorry, no students in this list.</li>

</ol>

 

Boolean Operators:

The {% if %} tags may use andnot and or operator to test several variables with a given variable:

Example usage: 

{% if student_list and teacher_list %}
    Both students and teachers are available.
{% endif %}

{% if not seat_arrangement %}
    There are no seat arrangement.
{% endif %}

{% if student_list or teacher_list %}
    There are some students or some teachers.
{% endif %}
You can also try this code with Online Python Compiler
Run Code

 

In the above example, we can see the usage of boolean operators with some dummy student and teacher lists. Refer to the official docs to learn more about Boolean Operators.

Include :

We can use include tags in Django templates to load one template in another and render it with the current context. The template name can be a variable or a (quoted) string, in either single or double-quotes.

Example usage: 

{% include "./header.html" %}
You can also try this code with Online Python Compiler
Run Code

 

Generally, the template name is relative to the template’s root directory. A string argument may be a relative path starting with ./ or ../.

Lorem :

The lorem tag provides random "lorem ipsum" Latin text. This is useful for delivering sample texts in templates.

The tag takes three optional arguments:

  1. count: The number of items (based on method) to output.
  2. method     
    • b – plain-text paragraphs (the default).
    • p – HTML paragraphs.
    • w – words.    
  3. random – When included, outputs random Latin words in place of the traditional lorem ipsum text.


Example usage: 

  • {% lorem %} will output the standard "lorem ipsum" paragraph.
  • {% lorem 2 p %} will output the standard "lorem ipsum" paragraph and two random sections, each wrapped in HTML tags.
  • {% lorem 2 w random %} will output two random Latin words.

Frequently Asked Questions

  1. What are some other tags in Django templates?
    Some other essential tags in Django are firstof, now, url, load, etc.
     
  2. What is the Django Template?
    A Django template is a python string or a text document marked up using the Django template language. It uses its syntax to deal with tags, variables, filters, etc. 

Key Takeaways

In this article, we learned about Tags in Django Template and used some commonly used tags in Django.

Don't stop here. Check out the blogs Best Django BooksTop 30 Basic Django Interview Questions: Part 1, and Top 30 Intermediate Django Interview Questions: Part 2.

We hope you found this blog helpful. Liked the blog? Then feel free to upvote and share it.

Live masterclass