Template Inheritance (Extends)
Template inheritance is how you avoid repeating HTML like headers/navbars/footers.
flowchart TD
A["child: {% extends 'base.html' %}"] --> B["Jinja renders BASE, not the child"]
B --> C{"base reaches a block"}
C -->|"child defines it"| D["the child's version is used"]
C -->|"child does not"| E["the base's default is used"]
D --> F{"does the child call super()?"}
F -->|yes| G["base content, then the child's -- appended"]
F -->|no| H["the base content is replaced"]
A --> I["text in the child outside any block"]
I --> J["silently discarded -- it never appears"]
Create a base layout
Section titled “Create a base layout”templates/base.html:
<!doctype html>
<html>
<head>
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
</nav>
<main>
{% block content %}{% endblock %}
</main>
</body>
</html>Extend it in a page
Section titled “Extend it in a page”templates/home.html:
{% extends "base.html" %}
{% block title %}Home{% endblock %}
{% block content %}
<h1>Welcome!</h1>
{% endblock %}Why this matters
Section titled “Why this matters”- One place to change your global layout
- Consistent design
- Easier to maintain as pages grow
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Create a Flask App
Section titled “Exercise 1 – Create a Flask App”Exercise 2 – Dynamic Route
Section titled “Exercise 2 – Dynamic Route”Exercise 3 – Return JSON
Section titled “Exercise 3 – Return JSON”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading