1. About Django templates
Django templates are a fundamental component of the Django web framework, responsible for generating dynamic HTML content. They are used to separate the presentation layer from the underlying business logic, providing a clean and organized way to display data to users.
Django templates play a crucial role in creating user-friendly and dynamic web applications by providing a flexible and efficient way to generate HTML content. They promote the principle of "Don't Repeat Yourself" (DRY) and contribute to the maintainability and scalability of Django projects.
The Django template language is designed to be simple, concise, and easy to read. It consists of a set of tags, filters, and template variables, which allow developers to include dynamic content and logic within the HTML templates. Templates can include variables that are replaced with actual data when the template is rendered, making it possible to create dynamic and personalized content for each user.
2. Key features of Django templates
A django template has many features that make it a powerful tool for separating the presentation layer from the application logic and designing dynamic, reusable, and secure web pages:
- Template Inheritance: Templates can be organized in a hierarchical structure, where child templates inherit the content and structure from parent templates. This enables code reuse and ensures consistency across different pages of a website.
- Template Tags: Django provides a variety of template tags that perform different actions or control the flow of the template. Tags are enclosed within curly braces {% ... %} and are used to loop over data, conditionally display content, or include other templates.
- Template Filters: Filters are used to modify the output of template variables before they are displayed. They are denoted by a pipe symbol (|) and can be applied to variables to perform various transformations or formatting operations.
- Template Variables: Variables represent data that is passed from the views (controllers) to the templates. They are enclosed within double curly braces {{ ... }} and are replaced with their corresponding values during template rendering.
- Comments: Django templates allow developers to include comments within the template code. Comments are useful for explaining the purpose or functionality of specific template sections.
- Escaping: Django automatically escapes template variables by default to prevent potential security vulnerabilities, such as cross-site scripting (XSS) attacks.
- Template Loading: Templates can be stored in various locations, and Django uses a template loader system to find and load templates from specified directories.
3. Configuration of the django template system
Before configuring the template system, you must first:
- Create a directory: named templates at the root of your project
- 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.
4. 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 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())
5. django template variables
The Django template system uses specific syntax to use and manipulate variables, tags, expressions, etc. Template variables are accessible by {{ template_variable_here! }} (double braces).
Example. (for a name variable with the value name = "Houssam" )
Welcome {{name}} # Which displays after execution: Welcome Houssam
6. Example of a django template variables
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:
7. System template tags
In a django template, tags provide logic in the rendering process. A template tag can be used in the following cases:
- to produce content,
- serve as a control structure (an if statement or for a loop),
- retrieve content from a database
- allow access to other model tags.
Syntax
Template tags are surrounded by:
{% and %}
and can contain any type of structure and variable.
7.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>
7.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%}
7.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 %}