Introduction to Templates in Django
What are Templates?
In Django, a template is a text file that defines the structure or layout of a file (like HTML) and can dynamically generate content using template tags and variables. Templates are used to separate the presentation logic from the business logic, making the code cleaner and more maintainable.
Creating a Template
Templates are stored in the templates
directory of your Django application. Django will look for templates in this directory by default.
Create a file named index.html
in the templates
directory:
templates/ index.html
Basic Template Syntax
Django templates use a language called the Django Template Language (DTL). Here are some basic elements:
- Variables: Variables are enclosed in double curly braces
{{ }}
. For example,{{ variable_name }}
. - Tags: Tags are enclosed in curly braces and percentage signs
{% %}
. For example,{% if condition %}
. - Filters: Filters are used to modify variables. They are added after a pipe symbol
|
. For example,{{ variable_name|filter }}
.
Example: Rendering a Template
Let's create a simple view to render our index.html
template.
Create a view in views.py
:
from django.shortcuts import render def index(request): return render(request, 'index.html')
Passing Context to Templates
You can pass data to templates using the context dictionary. This allows you to dynamically generate content.
Modify the index
view to pass context:
from django.shortcuts import render def index(request): context = { 'title': 'Welcome to Django Templates', 'description': 'This is a simple example of using templates in Django.' } return render(request, 'index.html', context)
Using Variables in Templates
Access the context variables in the template using double curly braces {{ }}
.
Modify index.html
to use the passed context:
{{ title }} {{ title }}
{{ description }}