By Md. Sabuj Sarker | 8/14/2017 | General |Beginners

Working with Django templates

Working with Django templates

One of the cool features in Django is that it has a built in sophisticated template engine. Django has a flexible ecosystem. If you have other requirements to using any other template engine you can easily do that. For example, you can use the Jinja2 template engine instead of the default Django template. Jinja2 is another template engine that was inspired by Django template.

In this article we will learn about using templates through examples. At first I am going to show templating in plain text and then with HTML markup. It doesn't matter to Django template whether you are using plain text or HTML. You get what you provide it with.

What is Django template

Django template (and any other template engine that is usable with Django) is nothing but a plain text file with a set of special syntaxes. Unlike many other templating systems it does not need to be XML, not xHTML, not HTML or some other alien language or syntax. Django follows a very flexible path. The template can be any type of text ranging from plain text to JSON along with HTML, XML or anything that can be written in plain text rather than in binary formats or encodings.

Getting started with examples

Before diving deep into Django template, let's start with some simple examples. It will help you to understand what I am going to teach you in this article.

Let's create a view function.

# views.py
from django.http import HttpResponse
def template_ex_view(request):
   return HttpResponse("This view was served from pain string without using any django template")



Configure our urlpatterns of app1.

# urls.py
from django.conf.urls import url
from app1.views import template_ex_view

urlpatterns = [
   url(r'^template-example$', template_ex_view)
]


Fire up the development server and go to localhost:8000/template_ex_view to see -

This view was served from pain string without using any django template

Now, let's do the same with Django template. Django prefers convention over configuration. Along with configuration for other things the configuration for template is already in place when you started the project.

Create a directory inside your app1 directory called templates and inside the templates directory create another directory named app1. We are going to place our Django template files in the inner app1 directory. Create a file named template1.html and write the following text in the file.

This view was served from a django template

Redefine the view as follows -

# views.py
from django.shortcuts import render
def template_ex_view(request):
   return render(request, "app1/template1.html")

Note: the render() function returns an HttpResponse.

Refresh your browser and you will see the following result.

This view was served from a django template

Without any magic we completed our job successfully with Django template. Now, we want to show a list of numbers with the help of our template.

# views.py
from django.shortcuts import render
def template_ex_view(request):
   no_list = [1, 2, 66, 77, 0]
   return render(request, "app1/template1.html", context={
       'no_list': no_list
   })

Now, in your template

The list of numbers:
{% for no in no_list%}
   * {{no}}
{% endfor %}

Go to that url to see the following output

The list of numbers:
   * 1
   * 2
   * 66
   * 77
   * 0

Does the syntax look familiar to you? Part of the syntax looks like Python. I am going to explain the unfamiliar parts in subsequent sections.

Template context

Python objects need to be passed to the templates so that we can display various data according to our needs with the help of Django template syntax. To do so we pass the objects inside a dictionary. The dictionary keys becomes the variables to the template and the associated object becomes the value of that variable. When we use the render() function, we pass the context with context keyword argument.

Django template syntax

Django template has its own syntax to display, manipulate, and control data and its flow. Django template revolves around four constructs:

  • Variables
  • Tags
  • Filters
  • Comments

Variables and interpolation {{ }}

In Django, if you want to display/print a value of some kind you need to put that inside {{ and }}. Inside that you need to put the variable name. The keys of context dictionary (or a dictionary like object) are the variable names to the template. If the associated object of the variable is not string then the Django template converts it to a string usually by calling __str__() on the object. We already have an example in the getting started section. Here is another simple example.

# views.py
from django.shortcuts import render
def template_ex_view(request):
   context = {
       'name': "Mr. Jhon Doe",
       'age': 36,
       'height': 6.7
   }
   return render(request, "app1/template1.html", context=context)

And the template:

Person details:
   Name: {{name}}
   Age: {{age}}
   Height: {{height}}

The result is:

Person details:
   Name: Mr. John Doe
   Age: 36
   Height: 6.7

Value from list and dictionary

If you want to get values from lists or dictionaries you need to use dot notation. Let's say, we have a variable called names inside our template and it contains list of people’s names. We get a name by index as follows:

1st person name {{ names.0 }}
2nd person name {{ names.1 }}

If you have a dictionary variable called name_to_age inside the template and you want to get  John’s age then you do it like this:

John's age {{ names.John }}

Calling a function

To call a function inside a Django function you do not need to use () and you cannot call functions that take any positional parameter. Let's say we have a variable named my_func that is a function. We call it just by putting it like a variable.

The result of the function call is: {{ my_func }}

Tags {% %}

Tags are a rather confusing name for what they are used for. It is not what you may think at first sight. It is not some HTML/XML tag that is used to structure or decorate your site. With the help of Django template you can control the flow of logic of the data you are going to display, you can display content with it, filter the results, interact with the database, and call functions. Every Django template tag has some kind of Python code that is backing it. You can create custom Django template tags and add that to your application. So, tags are used for various types of things.

Tags are written as {% tag something %} where tag is the name of the tag and optional something is the parameter of the tag. There can be zero or any number of parameters depending on the tag. Some tags have an end tag and some doesn't.

In the following sections I’ll explaining various types of template tags.

Conditional Django template tags

Django template is not a logicless template system. We often need to work with logic inside a template. To check something here we have if, elif, else like Python and we have endif to close the tag.

Look at the example below.

# views.py
from django.shortcuts import render
def template_ex_view(request):
   context = {
       'name': "Jhon",
       'age': 18,
       'height': 6
   }
   return render(request, "app1/template1.html", context=context)

And the template:

Person details:
   Name: {{name}}
   Age: {{age}}
   Height: {{height}}
{% if age > 16 %}
   {{name}} you are now old engough to go out of city alone. 
{% elif age >= 18 %}
   {{name}} you are now old engough to take alcohol. 
{% else %}
   {{name}} you are still a baby.
{% endif %}



Loops

Inside template we have for loops available. We cannot use while loops. Remember one thing that template syntax may look like python code but it is not. So, you cannot expect all of the functionality of python. We already used for loops in our getting started section. Looping is performed by for tag and it has an end tag.

# views.py
from django.shortcuts import render
def template_ex_view(request):
   no_list = range(5)
   return render(request, "app1/template1.html", context={
       'no_list': no_list
   })



Now, in your template:

The list of numbers:
{% for no in no_list%}
   * {{no}}
{% endfor %}

 

Tag for static files

static tag is used for generating URLs to static resources dynamically. Static files are usually kept inside the static directory of the apps directories. In production those are copied to another directory with the management command collectstatic. In our template (when written in HTML) if we write url just as is then we are putting our URLs statically instead of doing the same dynamically. Again if you change the configuration later for static files directory inside the apps' folders then your frontend part of the webapp will break for not loading static resources like images, JavaScript, CSS, etc.

Let's say we have the bootstrap.min.css file inside app1/static/app1/css. Now, if we want to dynamically generate a URL for the CSS we need to use the static template tag. Before you can use the static tag you need to load it and load is another template tag.

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
 <title>Bootstrap Example with django</title>
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="{% static 'app1/css/bootstrap.min.css' %}">
</head>
<body>



Filters

Filters just have one and only one responsibility which is to transform values. There are many built in filters and you can create your own custom template filters in Python. A filter is like a variable interpolation. Inside {{}} you put the variable name and with the variable name add a | followed by the filter you want to apply with optional/compulsory parameters. Here is a simple example to make values uppercase.

{{ some_variable:upper }}



Comments

Often we need to put some note in our code and we need to use a comment. In Django template we put comments between {# and #}. Here is an example.

{# hey I am a comment and I will not be present when the template is rendered #}



Template inheritance and block tags

A template system is not that useful if it does not provide you with a DRY way of working (DRY = Do Not Repeat Yourself). Instead of writing in pure HTML, XML, etc. we use template to make the system reusable. If a template engine does not provide you the way to reuse components then there is no point of wasting time behind that template engine. Django provides you with a good system of inheritance and hierarchy. Let's understand Django template inheritance with examples.

Create a base template with the name base.html:

<!DOCTYPE html>
<html>
<head>
   <title> </title>
</head>
<body>

</body>
</html> 



The above snippet of code is a common skeleton for every type of HTML file. So, what we want is to not repeat this part of code in any other HTML files/templates. But see we need to change the title in every HTML. To fill that gap we use block tags in a base template and put some value in inherited template. Bock tag accepts a parameter that is the name of the block that we can reference later. So, our base template looks like the following:

<!DOCTYPE html>
<html>
<head>
   <title> {% block title %} {% endblock %} </title>
</head>
<body>

</body>
</html>

But that's not the end of the story. We need to fill/change the content of body. So, we create another block:

<!DOCTYPE html>
<html>
<head>
   <title> {% block title %} {% endblock %} </title>
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>

Your block name doesn't have to be title and body - you can choose to name it whatever you like or fit your application logic.

Now, let's inherit our parent/base template in our child template. We tell the Django template engine that we want to inherit from another template with the help of the extends tag.

Create a file named chidl1.html

{% extends './base.html' %}

{% block title %} Child 1 Title {% endblock %}

{% block body %}
   <h1> I am inside a h1 tag in child 1 template </h1>
{% endblock %}

Now, if you render the child1.html template you get the following result.

<!DOCTYPE html>
<html>
<head>
   <title> Child 1 Title </title>
</head>
<body>
   <h1> I am inside a h1 tag in child 1 template </h1>
</body>
</html>

Without repeating our code we have constructed a complete HTML page.

Note: Django template does not support multi inheritance. If you want to inherit from multiple templates you can create a hierarchy of templates. Also you can use include tags for including multiple templates into one. But in that case the template context will not propagate down to the included template. So, try to use the extends tag where possible.

Other functions for template

Django template has other functions along with render()—render() is just a shortcut function. Among other functions get_template() and select_template() are notable ones. Please consult the official Django template documentation to get references on these and other functions for template.

 

*Stop by the homepage to search and compare SDKs, Dev Tools, and Libraries.

By Md. Sabuj Sarker | 8/14/2017 | General

{{CommentsModel.TotalCount}} Comments

Your Comment

{{CommentsModel.Message}}

Recent Stories

Top DiscoverSDK Experts

User photo
3355
Ashton Torrence
Web and Windows developer
GUI | Web and 11 more
View Profile
User photo
3220
Mendy Bennett
Experienced with Ad network & Ad servers.
Mobile | Ad Networks and 1 more
View Profile
User photo
3060
Karen Fitzgerald
7 years in Cross-Platform development.
Mobile | Cross Platform Frameworks
View Profile
Show All
X

Compare Products

Select up to three two products to compare by clicking on the compare icon () of each product.

{{compareToolModel.Error}}

Now comparing:

{{product.ProductName | createSubstring:25}} X
Compare Now