Template Inheritance (Extends)
Template inheritance is how you avoid repeating HTML like headers/navbars/footers.
Create a base layout
templates/base.htmltemplates/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><!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
templates/home.htmltemplates/home.html:
{% extends "base.html" %}
{% block title %}Home{% endblock %}
{% block content %}
<h1>Welcome!</h1>
{% endblock %}{% extends "base.html" %}
{% block title %}Home{% endblock %}
{% block content %}
<h1>Welcome!</h1>
{% endblock %}Why this matters
- One place to change your global layout
- Consistent design
- Easier to maintain as pages grow
๐งช Try It Yourself
Exercise 1 โ Create a Flask App
Exercise 2 โ Dynamic Route
Exercise 3 โ Return JSON
If this helped you, consider buying me a coffee โ
Buy me a coffeeWas this page helpful?
Let us know how we did
