Django Template Inheritance
- Learn how Django Template Inheritance helps create reusable page layouts.
What is Template Inheritance?
Template Inheritance allows one HTML template to:
Reuse another template
Avoid code duplication
Maintain a common layout across pages
Simple words:
👉 One main template → reused by all pagesWhy Template Inheritance is Important?
Without inheritance:
❌ Same header, footer, navbar repeated
❌ Hard to maintain large projectsWith inheritance:
Single base layout
Clean & professional code
Easy updates
Used in every real-world Django project
base.html
What is base.html?
base.html is:
The main layout template
Contains common structure
Header
Navbar
Footer
Other templates extend this file
Creating base.html
Base Template [ templates/myapp/base.html ]
Defines the common structure of the website.
<!DOCTYPE html>
<html>
<head>
<title>Django Website</title>
</head>
<body>
<header>
<h1>My Django Site</h1>
<hr>
</header>
{% block content %}
{% endblock %}
<footer>
<hr>
<p>© 2026 Django Training Institute</p>
</footer>
</body>
</html>
{% block content %} is a placeholder
block Tag
What is {% block %}?
Defines replaceable sections
Child templates override block content
Syntax:
{% block block_name %}{% endblock %}
Common Blocks
Code Example : Multiple Blocks in base.html
Using Multiple Blocks
More flexible layout design.
<head>
<title>{% block title %}Django Site{% endblock %}</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
extends Tag
What is {% extends %}?
Used in child templates
Inherits layout from base.html
Must be the first line of template
Syntax:
{% extends 'myapp/base.html' %}
Child Template using extends
Extending Base Template [ home.html ]
Home page inherits layout from base.
{% extends 'myapp/base.html' %}
{% block content %}
<h2>Home Page</h2>
<p>Welcome to Django Template Inheritance</p>
{% endblock %}
Only content section changes
Header & footer remain sameAnother Child Template
About Page using Inheritance
Different page, same layout.
{% extends 'myapp/base.html' %}
{% block content %}
<h2>About Us</h2>
<p>This is Django training institute</p>
{% endblock %}
How Template Inheritance Works (Flow)
1. Django loads child template
2. Finds {% extends %}
3. Loads base.html
4. Replaces {% block %} content
5. Renders final HTMLAdvantages of Template Inheritance
Reusable layout
Clean UI structure
Easy maintenance
Industry standard practice
Real-World Use Case
In real projects:
base.html → layout
home.html → content
login.html → content
dashboard.html → content
All pages look consistent