← Back to Chapters

Template Inheritance in Django

? Template Inheritance in Django

? Quick Overview

Django template inheritance allows you to reuse a common layout across multiple pages using {% extends %} and {% block %}.

? Key Concepts

  • Base (parent) templates
  • Child templates
  • Reusable blocks
  • DRY principle

? Syntax & Theory

The {% extends %} tag loads a parent template, while {% block %} defines replaceable sections.

? View Code Example
// Child template inheriting base.html
{% extends "base.html" %}

? Parent Template Example

? View Code Example
// Base template with a content block
<html>
<body>
<header>Header Content</header>
{% block content %}
<p>Default content for the page</p>
{% endblock %}
<footer>Footer Content</footer>
</body>
</html>

? Child Template Override

? View Code Example
// Overriding the content block
{% extends "base.html" %}
{% block content %}
<p>This is custom content for the child template.</p>
{% endblock %}

? Interactive Visualizer

Switch between views to see how the blocks are injected.

Site Header (Base)
{% block content %}

Default content for the page

{% endblock %}

? Live Explanation

The base template provides structure, and child templates inject only the required content, improving maintainability.

? Use Cases

  • Consistent website layout
  • Admin dashboards
  • Blogs and CMS systems

✅ Tips & Best Practices

  • Keep base templates minimal
  • Use meaningful block names
  • Avoid deeply nested blocks

? Try It Yourself

  • Create a base layout with header and footer
  • Override content in multiple child templates
  • Add sidebar blocks for practice