Template Inheritance in Django

Basic Concepts

  1. Base Template: A general template that includes common elements (like headers, footers, and navigation bars) used across multiple pages.
  2. Block Tags: Special tags in Django templates that define sections of the template that can be overridden by child templates.

Steps to Implement Template Inheritance

1. Create a Base Template

First, create a base template that includes the common layout for your website. For example, base.html:

<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}My Site{% endblock %}</title>
    <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}">
</head>
<body>
    <header>
        <h1>Welcome to My Site</h1>
    </header>

    <nav>
        <ul>
            <li><a href="{% url 'home' %}">Home</a></li>
            <li><a href="{% url 'about' %}">About</a></li>
            <li><a href="{% url 'contact' %}">Contact</a></li>
        </ul>
    </nav>

    <div class="content">
        {% block content %}{% endblock %}
    </div>

    <footer>
        <p>&copy; 2024 My Site</p>
    </footer>
</body>
</html>

2. Create a Child Template

Next, create a child template that extends the base template. For example, home.html:

{% extends 'base.html' %}

{% block title %}Home - My Site{% endblock %}

{% block content %}
    <h2>Home Page</h2>
    <p>Welcome to the home page of my awesome site!</p>
{% endblock %}

3. Render the Template in Views

In your Django views, render the child template. For example, in views.py:

from django.shortcuts import render

def home(request):
    return render(request, 'home.html')

4. URL Configuration

Ensure you have the appropriate URL configuration in urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    # other paths
]

Key Points to Remember

  • {% extends 'base.html' %}: This tag is used in the child template to specify the base template it extends.
  • Block Tags ({% block content %}{% endblock %}): Define sections in the base template that can be overridden by child templates.
  • Static Files: Use the {% static %} template tag to include static files like CSS and JavaScript.

Example Directory Structure

Here’s an example of what your directory structure might look like:

myproject/
    myapp/
        templates/
            base.html
            home.html
        views.py
        urls.py
    myproject/
        settings.py
        urls.py
        wsgi.py

By using template inheritance, you can efficiently manage and update the layout and design of your website while ensuring consistency across different pages.