extends Tag - Template Inheritance in Django
Django's extends tag enables reusing a base template across multiple pages, eliminating the need to duplicate HTML code. This ensures cleaner templates, easier maintenance, and a consistent layout throughout the site.
Syntax
{% extends 'base_template.html' %}
Example: Consider a project named 'geeksforgeeks' having an app named 'geeks'.
Project Structure
myproject/
templates/
geeks.html # Base template
extendedgeeks.html # Child template extending geeks.html
myapp/
views.py
urls.py
Step 1: Create a Base Template
Create a template that defines the main structure of your page with a content block that child templates can override.
In geeks.html:
<!DOCTYPE html>
<html>
<head>
<title>My Site</title>
</head>
<body>
<h1>Main Template Header</h1>
{% block content %}
<!-- Default content can go here -->
{% endblock %}
<footer>
<p>Footer information here</p>
</footer>
</body>
</html>
Step 2: Create a Child Template
Create a template that extends geeks.html and overrides the content block to provide page-specific content.
In extendedgeeks.html:
{% extends "geeks.html" %}
{% block content %}
<h2>GeeksForGeeks is the Best</h2>
<p>Welcome to the extended template example!</p>
{% endblock %}
Step 3: Define a View to Render the Template
In views.py:
from django.shortcuts import render
def geeks_view(request):
return render(request, "extendedgeeks.html")
Step 4: Configure URL Pattern
Add the URL path to access view.
In urls.py:
from django.urls import path
from .views import geeks_view
urlpatterns = [
path('', geeks_view, name='geeks_home'),
]
Step 5: Run the Development Server
Make sure your virtual environment is activated, then run:
python manage.py runserver
Accessing the URL http://127.0.0.1:8000/ will display:
- The header from geeks.html
- The content from extendedgeeks.html
- The footer from geeks.html

Using a Variable with the extends Tag
The extends Django template tag can also accept a variable instead of a hardcoded template name.
- If the variable evaluates to a string, Django treats it as the name of the parent template.
- If the variable evaluates to a Template object, Django uses that object as the parent template.
This feature allows dynamic selection of the base template at runtime, making template inheritance more flexible