A Django Template is a text-based file that defines the structure and layout of content (HTML, plain text, XML, etc.) to be presented to the user. Templates are a key part of Django’s MVT (Model-View-Template) architecture, allowing you to separate presentation logic from business logic.
Important Features of Django Templates
1. Dynamic Content: Use placeholders to insert data passed from views.
2. Template Tags: Add logic like loops, conditions, and filters to templates.
3. Reusable: Templates can include other templates and use common layouts.
4. Extensible: Use custom template tags and filters for advanced functionality.
Setting Up Django Templates
1. Create a Template Directory
By default, Django looks for templates in a templates
directory. Create it in your app or project folder:
myproject/
myapp/
templates/
myapp/
home.html
2. Configure Template Directory in Settings
In settings.py, add the templates directory to the DIRS option:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / "templates"], # Global template directory
'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',
],
},
},
]
Creating a Basic Template
1. Create a template file, e.g., templates/myapp/home.html:
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>{{ heading }}</h1>
<p>{{ message }}</p>
</body>
</html>
2. Pass data to the template from the view:
from django.shortcuts import render
def home(request):
context = {
'title': 'Home Page',
'heading': 'Welcome to Django Templates!',
'message': 'Django makes web development easy.',
}
return render(request, 'myapp/home.html', context)
3. Map the view to a URL in urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
Template Syntax
1. Variables
Variables are enclosed in {{ }}.
Example:
Welcome, {{ username }}!
2. Template Tags
Tags are enclosed in {% %}.
Example: Loops
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
Example: Conditions
{% if user.is_authenticated %}
<p>Welcome back, {{ user.username }}!</p>
{% else %}
<p>Please log in.</p>
{% endif %}
3. Filters
Filters modify variables.
Syntax: {{ variable|filter_name }}.
Example:
<p>Uppercase: {{ name|upper }}</p>
<p>Default: {{ greeting|default:"Hello" }}</p>
4. Include Other Templates
Example:
{% include 'myapp/navbar.html' %}