Extending Templates
Use template inheritance to avoid repeating HTML — create a base template and extend it in child templates with blocks.
Extending Templates
Most pages share the same navbar, footer, and head. Instead of repeating this code, Django supports template inheritance — define the shared structure once in a base template and override specific sections in child templates.
The Base Template
<!-- templates/base_layout.html -->
{% load static %}
<html>
<head>
<title>{% block title %}Django Blog{% endblock %}</title>
<link rel="stylesheet" href="{% static 'style.css' %}">
</head>
<body>
<nav>
<a href="/">Home</a>
<a href="/articles/">Articles</a>
</nav>
<div class="content">
{% block content %}
{% endblock %}
</div>
<footer>
<p>Copyright 2025</p>
</footer>
</body>
</html>
Extending the Base
<!-- templates/articles/article_list.html -->
{% extends 'base_layout.html' %}
{% block title %}Articles{% endblock %}
{% block content %}
<h1>All Articles</h1>
{% for article in articles %}
<div class="article">
<h2>{{ article.title }}</h2>
<p>{{ article.snippet }}</p>
</div>
{% endfor %}
{% endblock %}
How It Works
base_layout.html defines the skeleton + empty blocks
↓
Child template extends the base
↓
Child fills in the blocks with its own content
↓
Django merges them into a complete page
Key Takeaways
{% block name %}{% endblock %}defines replaceable sections{% extends 'base.html' %}inherits from the base template- Child templates only need to fill in the blocks — the rest comes from the base
- This eliminates HTML duplication across all pages