Django provides an efficient and convenient way to generate and display dynamic HTML pages using its template system. A template consists of a static part for HTML output, as well as a special syntax describing how dynamic content will be inserted. In an HTML file, we cannot write python code because the code is only interpreted by the python interpreter and not by the browser. We know that HTML is a static markup language, while Python is a dynamic programming language, for that we have to go through the template post.

 1 - Configuration of the django template system

Before configuring the template system, you must first:

  1. Create a directory named templates at the root of your project 
  2. Create an index.html file in the ‘templates’ directory

mysite/templates/index.html


<html>
<head>
<title>title</title>
</head>
<body>
<h2>Displaying a content via the system template !!!</h2>
<p>MyBody</p>
</body>

To configure the template system, we must provide certain entries in the mysite/settings.py file:

mysite/settings.py
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',
],
},
},
]

This code tells the django system that the template directory is ‘templates’ by default.

2 - Loading the template 

To load the template in a django application, just call it in the views.py file via the get_template() method: myapp/views.py

myapp/views.py 
from django.shortcuts import render  
#importing loading from django template
from django.template import loader
# Create your views here.
from django.http import HttpResponse
def index(request):
# getting our template
template = loader.get_template('index.html')
# rendering the template in HttpResponse
return HttpResponse(template.render())

3 - django template variables 

The Django template system uses specific syntax to use and manipulate variables, tags, expressions, etc. Template variables are accessible by {{ }} (double braces).

Example. (for a name variable with the value name='Houssam')

Welcome {{name}}

Which displays after execution: Welcome Houssam

4 - Example of a django template variable 

Template variables are declared in the views.py file and displayed in the index.html file of the template.

Example myapp/views.py 

from django.shortcuts import render
#importing loading from django template
from django.template import loader
# Create your views here.
from django.http import HttpResponse
def index (request):
template = loader.get_template ('index.html') # getting our template
data = {
'Institute': 'CRMEF OUJDA'
}
# rendering the template in HttpResponse
return HttpResponse (template.render (data))

The variable 'Institute' can now be called at the level of the index.html file of the template: myapp/templates/index.html

<!DOCTYPE html>  
<html>
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<h2>Content displayed through the system template !!!</h2>
<h3>Welcome to : {{ Institute }}</h3>
</body>
</html>

Which displays at the output:

5 - System template tags 

 In a template, tags provide logic in the rendering process. A template tag can be used in the following cases:

  1. to produce content, 
  2.  serve as a control structure (an if statement or for a loop), 
  3.  retrieve content from a database 
  4. allow access to other model tags.

Syntax :

Template tags are surrounded by:

{% and %}

and can contain any type of structure and variable.

5.1 - Case of the conditional structure if

{% if condition%}
Results display
{% else%}
other results
{% endif%}

Example. structure if… else… 

We define an age variable in the myapp/views.py file:   

myapp/views.py
from django.shortcuts import render
#importing loading from django template
from django.template import loader
# Create your views here.
from django.http import HttpResponse
def index(request):
template = loader.get_template('index.html') # getting our template
Age = {
'age':14,
}
# rendering the template in HttpResponse
return HttpResponse(template.render(Age))
We apply the conditional structure If… Else… at the level of the file myapp/templates/index.html 

myapp/templates/index.html
<html>
<head>
<meta charset = "UTF-8">
<title> Index </title>
</head>
<body>
<h2> Major and minor test! </h2>
<h3> {% if age <18%} </h3>
<p> Your age is: {{age}} you are minor ! </p>
{% else%}
<p> Your age is: {{age}} you are major! </p>
{% endif%}
</body>
</html>

5.2 - The For… End For tag

The for tag allows us to cycle through a sequence. We can use the for tag to execute repeated instructions, to browse the contents of a list, a tuple, a dictionary, etc. Here is the syntax of the for tag:

{% for x in list%}
The value of x is: {{x}}
{% endfor%}

5.3 - Comments tag

The django template system also allows you to manage comments using the following syntax:

{# This is a single line comment #}

Comment you write using this syntax will not be rendered in the HTML source code. In addition, you cannot expand this comment on multiple lines. For example:

{# This is not
a comment !#}

In order to be able to write comments on several lines, we use the following syntax:

{% comment %}
This is a comment
in multiple
lines!
{% endcomment %}

Younes Derfoufi
my-courses.net

Leave a Reply