Django
Beginner
1 min read
Template Inheritance with extends and block
Example
{# templates/base.html — the parent layout #}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}My Blog{% endblock %}</title>
{% block extra_css %}{% endblock %}
</head>
<body>
<header>
<nav>
<a href="{% url 'post-list' %}">Home</a>
{% if user.is_authenticated %}
<a href="{% url 'post-create' %}">New Post</a>
<a href="{% url 'logout' %}">Logout</a>
{% else %}
<a href="{% url 'login' %}">Login</a>
{% endif %}
</nav>
</header>
<main>
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">{{ message }}</div>
{% endfor %}
{% endif %}
{% block content %}{% endblock %}
</main>
<footer><p>© 2024 My Blog</p></footer>
{% block extra_js %}{% endblock %}
</body>
</html>
{# templates/blog/post_detail.html — child template #}
{% extends "base.html" %}
{% block title %}{{ post.title }} | My Blog{% endblock %}
{% block content %}
<article>
<h1>{{ post.title }}</h1>
<p>{{ post.published_at|date:"F j, Y" }}</p>
<div class="body">{{ post.body|linebreaks }}</div>
</article>
{% include "blog/partials/comment_form.html" with form=form post=post %}
{% endblock %}
Related Resources
Django Reference
Complete tag & property list
Django How-To Guides
Step-by-step practical guides
Django Exercises
Practice what you've learned
More in Django