Reading — step 1 of 5
Read
Template Inheritance
DRY principle: define a layout once, customize per page.
Base template (base.html):
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}Default{% endblock %}</title>
</head>
<body>
<header>{% block header %}<h1>Site</h1>{% endblock %}</header>
<main>{% block content %}{% endblock %}</main>
<footer>© 2024</footer>
</body>
</html>
Child template:
{% extends "base.html" %}
{% block title %}My Page{% endblock %}
{% block content %}
<p>Hello, {{ name }}!</p>
{% endblock %}
Renders:
<!DOCTYPE html>
<html>
<head><title>My Page</title></head>
<body>
<header><h1>Site</h1></header>
<main><p>Hello, Alice!</p></main>
<footer>© 2024</footer>
</body>
</html>
Header block not overridden → falls back to base's content.
Implementation:
{% include "partial.html" %}: inline render another template. No inheritance; just substitution. Useful for reusable components (nav, footer).
{% import "macros.html" as m %} + {{ m.button("Click me") }}: define reusable macros. Like functions in templates.
Multi-level inheritance: child extends grandchild extends base. Resolve from child up.
Block scoping: by default, base block's variables visible. Child's block can ALSO see its own context. {% block content scoped %} exposes outer scope explicitly.
Block override approaches:
- Replace: child's block replaces base's.
- Append:
{{ super() }}calls parent's block first, then add to it.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…