Author avatar

Gaurav Singhal

Introduction to Django Templates

Gaurav Singhal

  • Nov 18, 2020
  • 7 Min read
  • 73 Views
  • Nov 18, 2020
  • 7 Min read
  • 73 Views
Web Development
Django
Back End Web Development
Server-side Frameworks

Introduction

In the Django MTV model, the template is the presentation layer. This layer interacts with the user, sends the requests to the views, and responds to the user.

Django templates deal with HTML/CSS/JS. All rendering is handled in templates. Other than the basic constructs of HTML/CSS/JS, Django comes with templating language to render dynamic data in the form of templates. In this guide, you will learn about the Django templates and the language constructs that are necessary to build a Django application.

Why Django Templates

Django template is a text document or Python string marked up that uses Django template language. Django keeps the logic and code separate from the design. It is essential to know that Django templates do not contain the embedded code of Python into HTML.

Django templates follow the DRY (do not repeat yourself) design principle, which requires developers to not repeat while designing a Django application. Django templates employ several other notions, such as template inheritance, tags, variables, filters, comments, etc.

Template Configuration

To configure the Django template system, go to the settings.py file and update the DIRS to the path of the templates folder. Generally, the templates folder is created and kept in the sample directory where manage.py lives. This templates folder contains all the templates you will create in different Django Apps.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import os

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
python

Alternatively, you can maintain a template folder for each app separately. If you are maintaining the template for every app separately, you don't need to update the DIRS in settings.py. Make sure that your app is added in INSTALLED_APPS in settings.py .

The Django Template Language

In the Django template language, the syntax involves four major constructs.

1. Variables

Variables output the value from the context. The context is generally a dict-like object (mapping variable name with its respective value) passed from views.

The basic syntax is:

1
{{ variable_name }}
django

For example, if you render the context set as shown below ...

1
2
3
4
5
6
7
8
9
10
11
12
from django.shortcuts import render

def my_view(request):
    context = {
        "author": "Gaurav Singhal",
        "website": {
            "domain": "https://pluralsight.com",
            "views": 200
        },
        "odds": [1, 3, 5]
    }
    return render(request, "index.html", context)
python

... you can access it in template index.html as :

1
2
3
{{author}}
{{website.domain}}
{{website.views}}
django

2. Tags

Tags give logic to the template language to render the content logically.

The basic syntax is:

1
{% tag_name %}
django

Example:

1
{% if user.is_authenticated %}Howdy, {{ user.username }}, How are you {% endif %}
django

There are several tags which are used in templates Some of them are:

  • If/Else:

    1
    2
    3
    4
    5
    {% if condition %} 
    	renders if body 
    {% else %} 
        renders else body 
    {% endif %}
    django
  • For loop

    1
    2
    3
    {% for odd in odds %}
    {{odd}}
    {% endfor %}
    django
  • include

This is used to load a template and render it to the current context. It is very useful for creating several components separately, such as navbar, footer, etc., and then including them in several templates.

1
{% include template_name %}
django
  • block

This defines the block to be overridden by the child template. You will get a better idea of blocks when we discuss template inheritance .

1
2
{% block content %}
{% endblock %}
django

You can read more about built-in tags in the Django docs.

3. Filters

The filter is used to transform the value of the variable and tag argument.

It can be used as:

1
{{ my_variable | filter }}
django

For example:

1
{{ my_date|date:"Y-m-d" }}
django

You can read more about filter and several built-in filters in the Django docs.

4. Comments

You can easily add a comment in Django templates:

1
{# Comment here. It won't be rendered #}
django

Template Inheritance

One of the most powerful parts of the Django template engine is template inheritance. This allows you to build a base skeleton template that contains all the base/common elements and defines blocks in a child/derived template after extending the base template. It is easier to understand in practice. Let's first create a base.html.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<html>
   <head>
      <title>
         {% block title %}Base title{% endblock %}
      </title>
        {% comment %} This Bootsrap css is added to all pages {% endcomment %}
      <link rel="stylesheet" href = "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
   </head>
   <body>
    <p>
    Body content which remains in all the pages
    </p>
      {% block content %}
         Body content
      {% endblock %}
   </body>
</html>
django

Now create a child template and save it as index.html.

1
2
3
4
5
6
7
8
9
{% extends 'base.html' %}

{% block title %}
This is index title
{% endblock title %}

{% block content %}
Main content of index.html
{% endblock content %}
django

Now when you render the index.html from the views, you will get the following output:

1
2
3
Body content which remains in all the pages

Main content of index.html

Conclusion

A Django template deals with passing information from a Django view to the browser and is considered the basic building block of a dynamic Django application. You can refer to the Django documentation to learn Django template in depth.

If you have any questions, feel free to reach out to me at Codealphabet.

1