Template Inheritance & Layout Composition
Template Inheritance & Layout Composition
Copying and pasting navigation bars, footers, head meta tags, and stylesheet imports across dozens of HTML pages is a recipe for maintenance nightmares. Template inheritance is Jinja2's most powerful feature, enabling you to build a master skeleton template containing common elements while child templates override specific content blocks.
1. The Master Skeleton (templates/base.html)
The base template defines the universal structure of your website and marks customizable areas using {% block <name> %}{% endblock %}:
2. Child Templates ({% extends %})
Child templates declare which base template they inherit from using {% extends "base.html" %}. This must be the very first tag in the child template file!
3. Preserving Parent Content with super()
If a child template wants to add content to a block without completely overwriting what the parent template defined, call {{ super() }}:
4. Modular Partials with {% include %}
While {% extends %} provides top-down vertical page scaffolding, {% include %} allows horizontal inclusion of modular template snippets (e.g. newsletter banners, navigation bars, modals):
Practice Quiz
{% extends %} in a child template?{% extends %} and {% include %}?title, content, extra_js) within the same file?Jinja2 Macros & Reusable UI Components
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Control Structures, Loops & Conditionals | Jinja2 Macros & Reusable UI Components |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.