How does Django's template inheritance work, and what is the purpose of the {% block %} and {% extends %} tags?
Last updated
Template inheritance lets a child template reuse a parent's structure and override only specific regions. {% extends %} declares the parent, and {% block %} defines named, overridable sections.
{% extends %}:Must be the first tag in the child template; it names the base template the child builds on.
The child only supplies content for blocks; everything else comes from the parent.
{% block %}:Defines a named region in the parent (e.g.
{% block content %}) that children can replace.Content inside a block in the parent acts as a default if the child doesn't override it.
Overriding and extending:
A child overrides a block by redefining it with the same name.
Use
{{ block.super }}to include the parent's block content instead of fully replacing it.
Benefit: a single base layout (header, nav, footer) avoids duplication across pages (DRY).
[lang:html]
<!-- base.html -->
<title>{% block title %}Site{% endblock %}</title>
<body>{% block content %}{% endblock %}</body>
<!-- page.html -->
{% extends "base.html" %}
{% block title %}Home{% endblock %}
{% block content %}<h1>Welcome</h1>{% endblock %}