python / intermediate
Snippet
Django Template Inheritance and Block Structure
Django templates use inheritance to create consistent layouts. The base template defines blocks that child templates can override. This promotes DRY (Don't Repeat Yourself) principles and enables template composition. Unmatched blocks use the parent template's default content.
snippet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
{# base.html #}<!DOCTYPE html><html lang="{{ LANGUAGE_CODE }}"><head><meta charset="UTF-8"><title>{% block title %}Capypad{% endblock %}</title>{% block extra_head %}{% endblock %}</head><body><header>{% block header %}{% endblock %}</header><main>{% block content %}{% endblock %}</main><footer>{% block footer %}© 2024{% endblock %}</footer></body></html>{# child.html #}{% extends 'base.html' %}{% block title %}My Blog{% endblock %}{% block content %}<h1>{{ post.title }}</h1><p>{{ post.body|linebreaks }}</p>{% endblock %}{% block extra_head %}<link rel="stylesheet" href="custom.css">{% endblock %}
django
Breakdown
1
{% block title %}Capypad{% endblock %}
Defines a replaceable block with default content 'Capypad'
2
{% block extra_head %}{% endblock %}
Empty block allows children to add CSS/js without forced content
3
{% extends 'base.html' %}
Specifies this template inherits from base.html
4
{{ post.body|linebreaks }}
The linebreaks filter converts newlines to HTML paragraph tags
5
{% block extra_head %}<link...{% endblock %}
Child adds content to parent's empty block without replacing it entirely