Template Inheritance & Blocks
Template inheritance is Django's most powerful template feature. You create a base template with common elements (header, nav, footer) and child templates that override specific blocks. This eliminates HTML duplication across pages.
20 min•By Priygop Team•Updated 2026
How Inheritance Works
- Create a base.html with {% block %} placeholders
- Child templates use {% extends 'base.html' %}
- Override blocks with {% block name %} content {% endblock %}
- {{ block.super }} inserts parent block's content
- You can nest inheritance: base.html → page.html → detail.html
- {% extends %} must be the FIRST tag in a child template
- Blocks not overridden keep the parent's default content
Template Inheritance
Template Inheritance
# templates/base.html — Base template
# <!DOCTYPE html>
# <html>
# <head>
# <title>{% block title %}My Site{% endblock %}</title>
# {% block extra_css %}{% endblock %}
# </head>
# <body>
# <nav>
# <a href="{% url 'home' %}">Home</a>
# <a href="{% url 'blog:list' %}">Blog</a>
# </nav>
#
# <main>
# {% block content %}{% endblock %}
# </main>
#
# <footer>Copyright 2026</footer>
# {% block extra_js %}{% endblock %}
# </body>
# </html>
# blog/templates/blog/list.html — Child template
# {% extends 'base.html' %}
#
# {% block title %}Blog Posts{% endblock %}
#
# {% block content %}
# <h1>All Posts</h1>
# {% for post in posts %}
# <h2>{{ post.title }}</h2>
# <p>{{ post.content|truncatewords:30 }}</p>
# {% endfor %}
# {% endblock %}Tip
Tip
Create a base.html with {% block content %}{% endblock %} and extend it everywhere. Change the layout once, update all pages.
Diagram
Loading diagram…
QuerySets are LAZY — no DB hit until evaluated.
Common Mistake
Warning
Duplicating HTML across templates. If you copy-paste <head> or <nav> into multiple files, you need template inheritance.
Practice Task
Note
(1) Create base.html with nav and footer. (2) Extend it in 3 child templates. (3) Use {% block title %} for page titles.
Quick Quiz
Key Takeaways
- Template inheritance is Django's most powerful template feature.
- Create a base.html with {% block %} placeholders
- Child templates use {% extends 'base.html' %}
- Override blocks with {% block name %} content {% endblock %}