English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Django Template System

 Django can separate Python and HTML separately, Python code/Variables enter the view and HTML template. Django connects these two, depending on the rendering function and Django template language.

Rendering function

This function has three parameters −

Request − Initialize the requestTemplate path − This is the path relative to the variable in the project's settings.py file to the TEMPLATE_DIRS option.Parameter dictionary − The dictionary contains all the variables required in the template. These variables can be created or used by locals() through all local variables declared in the view.

Django Template Language (DTL)

The Django template engine provides a small language to define the application layer facing the user.

Display variables

The variable is displayed as follows: {{variable}}. The template is replaced by the variables sent by the view in the third parameter of the render function. Let's change hello.html to display the current date:

hello.html

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
<html> 
    <body>
       Hello World!!!<p>Today is {{today}}</p>
    </body> 
 </html>

Then, our view will change to -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
def hello(request):
    today = datetime.datetime.now().date()
    return render(request, "hello.html", {"today": today})

Now, we will get the following output when accessing the URL /myapp/hello after−

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
Hello World!!!
 Today is Sept. 11, 2015

As you may have noticed, if the variable is not a string, Django will use the __str__ method to display it; and by the same principle, you can access the properties of the object, just like in Python. For example: if we want to display the year of the date, the variable here is: {{today.year}}.

Filter

They can help you display modified variables. The structure of the filter is as follows: {{var|filters}}.

A simple example −

{{string|truncatewords:8The filter truncates the string, so only the first part is visible80 characters.

       {{string|lower}} − Convert characters to lowercase            {{string|escape|linebreaks}} − Escape the string content and then convert line breaks to tags.    

You can also set default variables.

Tags

Tags can perform the following operations: if condition, for loop, template inheritance, and more.

if tags

Just like in Python, you can use if, else, and elif in templates −

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
<html>
    <body>
       Hello World!!!<p>Today is {{today}}</p>
       We are
       {% if today.day == 1 %}
       the first day of the month.
       {% elif today == 30 %}
       the last day of the month.
       {% else %}
       I don't know.
       {% endif %}
    </body>
 </html>

In this new template, according to the date of the day, the template will display this value.

for tags

Just like 'if', we have 'for' tags, which are used exactly like in Python. Let's change the hello view list sent to our template −

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
def hello(request):
    today = datetime.datetime.now().date()
    daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    return render(request, 'hello.html', {'today': today, 'days_of_week': daysOfWeek})

This template is used to display lists {{ for }} −

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
<html>
    <body>
       Hello World!!!<p>Today is {{today}}</p>
       We are
       {% if today.day == 1 %}
       the first day of the month.
       {% elif today == 30 %}
       the last day of the month.
       {% else %}
       I don't know.
       {% endif %}
       <p>
          {% for day in days_of_week %}
          {{day}}
       </p>
 
       {% endfor %}
    </body>
 </html>

We should get the output content as follows −

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
Hello World!!!
 Today is Sept. 11, 2015
 We are I don't know.
 Mon
 Tue
 Wed
 Thu
 Fri
 Sat
 Sun

Block and extension tags

The template system is an incomplete template inheritance. When you design the meaning of a template, the child template fills in the main template according to its needs, just like a special CSS may be needed for a selected tab on a page.

Let's modify the hello.html template to inherit from main_template.html.

main_template.html

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
<html>
    <head> 
       <title>
          {% block title %}Page Title{% endblock %}
       </title> 
    </head>
 
    <body> 
       {% block content %}
          Body content
       {% endblock %} 
    </body>
 </html>

hello.html

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
{% extends "main_template.html" %}
 {% block title %}My Hello Page{% endblock %}
 {% block content %}
 Hello World!!!<p>Today is {{today}}</p>
 We are
 {% if today.day == 1 %}
 the first day of the month.
 {% elif today == 30 %}
 the last day of the month.
 {% else %}
 I don't know.
 {% endif %}
 <p>
    {% for day in days_of_week %}
    {{day}}
 </p>
 {% endfor %}
 {% endblock %}

In the above example, at the call /myapp/hello, we will still get the same result as before, but now we rely on the extension and do not need to refactor the code-−

In main_template.html, we define the use of tag blocks. The title bar block will contain the page title, and the content block will be the main content of the page. In Home.html, using extended inheritance from main_template.html, we use the above block definitions (content and title).

Comment tags

Comment tags are used for template comments, not HTML comments, and they will not appear on the HTML page. It can be a file or just a line of comment code.