0 Tage Serie
python / intermediate
Snippet

Django Template-Vererbung und Block-Struktur

Django-Templates verwenden Vererbung, um konsistente Layouts zu erstellen. Das Basis-Template definiert Blöcke, die Kind-Templates überschreiben können. Dies fördert das DRY-Prinzip (Don't Repeat Yourself) und ermöglicht Template-Komposition. Nicht überschriebene Blöcke verwenden den Standardinhalt des Eltern-Templates.

snippet.py
python
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
Erklärung
1
{% block title %}Capypad{% endblock %}
Definiert einen ersetzbaren Block mit Standardinhalt 'Capypad'
2
{% block extra_head %}{% endblock %}
Leerer Block erlaubt Kindern CSS/JS hinzuzufügen ohne erzwungenen Inhalt
3
{% extends 'base.html' %}
Gibt an, dass dieses Template von base.html erbt
4
{{ post.body|linebreaks }}
Der linebreaks-Filter konvertiert Zeilenumbrüche zu HTML-Absatz-Tags
5
{% block extra_head %}<link...{% endblock %}
Kind fügt Inhalt zum leeren Block des Parents hinzu