Django Template

A Django template is an HTML file that allows you to display dynamic data from your Django application. It serves as the presentation layer in Django’s MVT (Model-View-Template) architecture, separating the user interface from business logic.

Templates use the Django Template Language (DTL), which provides variables, tags, and filters to render dynamic content.

Why Use Django Templates?

  • Separate presentation from application logic.
  • Display dynamic data on web pages.
  • Reuse layouts and components.
  • Improve code maintainability and readability.

Example Template

<!DOCTYPE html>
<html>
<head>
    <title>Home Page</title>
</head>
<body>
    <h1>Welcome, {{ username }}</h1>
    <p>Today is {{ date }}</p>
</body>
</html>

Example View

from django.shortcuts import render
from datetime import date

def home(request):
    return render(request, 'home.html', {
        'username': 'Tarun',
        'date': date.today()
    })

When the page is requested, Django replaces the variables with actual values and sends the rendered HTML to the browser.

Template Variables

Variables display dynamic data.

<h1>{{ username }}</h1>
<p>{{ email }}</p>

Template Tags

Tags add logic to templates.

If Tag

{% if user.is_authenticated %}
    <p>Welcome Back!</p>
{% endif %}

For Loop

{% for product in products %}
    <p>{{ product.name }}</p>
{% endfor %}

Template Inheritance

Template inheritance allows multiple pages to share a common layout.

base.html

<html>
<head>
    <title>My Website</title>
</head>
<body>
    {% block content %}
    {% endblock %}
</body>
</html>

home.html

{% extends 'base.html' %}

{% block content %}
<h1>Home Page</h1>
{% endblock %}

Include Tag

The {% include %} tag allows you to reuse small template fragments such as headers, footers, sidebars, and navigation menus.

header.html

<header>
    <h1>My Website</h1>
</header>

home.html

{% include 'header.html' %}

<h2>Welcome to the Home Page</h2>

This helps avoid repeating the same code across multiple templates and makes maintenance easier.

Benefits of Django Templates

  • Dynamic content rendering
  • Clean separation of concerns
  • Reusable components with include
  • Shared layouts with template inheritance
  • Easier maintenance and scalability