Django Templates
Templates are the third and most important part of Django’s MVT Structure. A template in Django is basically written in HTML, CSS, and Javascript in a .html file. Django framework efficiently handles and generates dynamically HTML web pages that are visible to the end-user. Django mainly functions with a backend so, in order to provide a frontend and provide a layout to our website, we use templates. There are two methods of adding the template to our website depending on our needs.
- We can use a single template directory which will be spread over the entire project.
- For each app of our project, we can create a different template directory.
For our current project, we will create a single template directory that will be spread over the entire project for simplicity. App-level templates are generally used in big projects or in case we want to provide a different layout to each component of our webpage.
Configuration
Django Templates can be configured in app_name/settings.py,
Python3
TEMPLATES = [ { # Template backend to be used, For example Jinja 'BACKEND' : 'django.template.backends.django.DjangoTemplates' , # directories for templates 'DIRS' : [], 'APP_DIRS' : True , # options to configure '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' , ], }, }, ] |
Now let’s create a template directory and add that directory in the above configuration. After creating the templates folder our directory should look like this –
Let’s add the location of this directory in our templates dictionary.
Python3
TEMPLATES = [ { 'BACKEND' : 'django.template.backends.django.DjangoTemplates' , # adding the location of our templates directory 'DIRS' : [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' , ], }, }, ] |
After adding the location of the template directory we will create a simple HTML file and name it as index.html and then we will render this file from our view function.
HTML file:
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < meta http-equiv = "X-UA-Compatible" content = "ie=edge" > < title >Homepage</ title > </ head > < body > < h1 >Welcome to w3wiki</ h1 > </ body > </ html > |
To render this HTML on our site we need to use the render function from the django.shortcuts. Below is the updated view function.
views.py
Python3
from django.shortcuts import render # create a function def geeks_view(request): return render(request, "index.html" ) |
If we head to our website we will see the HTML data on our site as –
The Django Templates not only show static data but also the data from different databases connected to the application through a context dictionary. Let’s see this with an example. We will try to render the content of our database dynamically to our website.
First, let’s update our views.py file. In this file we will get our data from our database and then pass this database as a dictionary to our HTML file.
views.py
Python3
from django.shortcuts import render from .models import GeeksModel # create a function def geeks_view(request): content = GeeksModel.objects. all () context = { 'content' : content } return render(request, "index.html" , context = context) |
index.html
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < meta http-equiv = "X-UA-Compatible" content = "ie=edge" > < title >Homepage</ title > </ head > < body > {% for data in content %} < h2 >{{data.title}}</ h2 > < img src = "{{ data.image.url }}" alt = "" > < p >< strong >Description:</ strong >{{data.description}}</ p > < p >< strong >Created On:</ strong >{{data.created_on}}</ p > {% endfor %} </ body > </ html > |
Our website now looks like this –
Now if we add more data to our site then that data will also be shown to our site without making any changes to our HTML or views.py. Let’s add some data and then see if it works or not.
Django template language
This is one of the most important facilities provided by Django Templates. A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. As we used for the loop in the above example, we used it as a tag. similarly, we can use various other conditions such as if, else, if-else, empty, etc. The main characteristics of Django Template language are Variables, Tags, Filters, and Comments.
Variables output a value from the context, which is a dict-like object mapping keys to values. The context object we sent from the view can be accessed in the template using variables of Django Template.
Syntax
{{ variable_name }}
Tags provide arbitrary logic in the rendering process. For example, a tag can output content, serve as a control structure e.g. an “if” statement or a “for” loop, grab content from a database, or even enable access to other template tags.
Syntax
{% tag_name %}
Django Template Engine provides filters that are used to transform the values of variables and tag arguments. We have already discussed major Django Template Tags. Tags can’t modify the value of a variable whereas filters can be used for incrementing the value of a variable or modifying it to one’s own need.
Syntax
{{ variable_name | filter_name }}
Template ignores everything between {% comment %} and {% end comment %}. An optional note may be inserted in the first tag. For example, this is useful when commenting out code for documenting why the code was disabled.
Syntax
{% comment 'comment_name' %} {% endcomment %}
Template Inheritance
The most powerful and thus the most complex part of Django’s template engine is template inheritance. Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override. extends tag is used for the inheritance of templates in Django. One needs to repeat the same code again and again. Using extends we can inherit templates as well as variables.
Syntax
{% extends 'template_name.html' %}
Example: Assume the following directory structure:
dir1/ template.html base2.html my/ base3.html base1.html
In template.html, the following paths would be valid:
HTML
{% extends "./base2.html" %} {% extends "../base1.html" %} {% extends "./my/base3.html" %} |
Refer to the below articles to get more information about Django Templates –
Python Web Development With Django
Python Django is a web framework that allows to quickly create efficient web pages. Django is also called batteries included framework because it provides built-in features such as Django Admin Interface, default database – SQLite3, etc. When you’re building a website, you always need a similar set of components: a way to handle user authentication (signing up, signing in, signing out), a management panel for your website, forms, a way to upload files, etc. Django gives you ready-made components to use.