extends - Django Template Tags
Django’s {% extends %} tag allows you to reuse a base template across multiple pages, so you don’t have to repeat the same HTML code in every template. This makes your templates cleaner, easier to maintain, and helps keep a consistent layout throughout your site.
Syntax:
{% extends 'base_template.html' %}
Example: Assume the following directory structure:
project_root/
templates/
base.html
app/
child.html
You would extend the base template in child.html like this:
{% extends "base.html" %}
or, if the base is inside the app folder:
{% extends "app/base.html" %}
extends - Django template Tags Explanation
Illustration of How to use extends tag in Django templates using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
Example 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 (geeks.html)
This template defines the main structure of your page with a content block that child templates can override.
<!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 (extendedgeeks.html)
This template extends geeks.html and overrides the content block to provide page-specific content.
{% 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 (views.py)
In your Django app’s views.py:
from django.shortcuts import render
def geeks_view(request):
return render(request, "extendedgeeks.html")
Step 4: Configure URL Pattern (urls.py)
Add the URL path to access your 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
Let's check if data is displayed from both the templates in extendedgeeks.html by visiting URL- http://127.0.0.1:8000/ in your browser, you should see:
- The header from geeks.html
- The content from extendedgeeks.html
- The footer from geeks.html
Note: {% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.
Also Read: Template Filters