Template inheritance allows multiple HTML pages to share a common layout using Jinja templates. A base template contains common sections such as headers, footers and navigation bars, while other templates inherit and customize specific parts of that layout.
Implementing Template Inheritance
Step 1: Set Up a Flask App
First, create a basic Flask application with multiple routes.
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
@app.route('/about')
def about():
return render_template('about.html')
if __name__ == '__main__':
app.run(debug=True)
Explanation:
- @app.route('/') maps the home page route.
- @app.route('/about') maps the about page route.
- render_template() renders the required HTML template.
Step 2: Create a Base Template
Create a file named base.html inside the templates folder. This file contains the common layout shared by all pages.
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>My Flask App</title>
</head>
<body>
<h1>Welcome to My Website</h1>
<nav>
<a href="/">Home</a> |
<a href="/about">About</a>
</nav>
{% block content %}{% endblock %}
</body>
</html>
Explanation:
- {% block content %} creates a placeholder for page-specific content.
- Common elements like headings and navigation bars are written only once in base.html.
Step 3: Create Child Templates
Create a file named home.html inside the templates folder.
home.html
{% extends "base.html" %}
{% block content %}
<h2>Home Page</h2>
<p>Welcome to the homepage of our Flask app!</p>
{% endblock %}
Explanation:
- {% extends "base.html" %} inherits the layout from base.html.
- {% block content %} replaces the content section defined in the base template.
Step 4: Create a Child Template for About Page
Create a file named about.html inside the templates folder.
about.html
{% extends "base.html" %}
{% block content %}
<h2>About Us</h2>
<p>This is the about page of our Flask app.</p>
{% endblock %}
Explanation:
- about.html reuses the same layout from base.html.
- Only the content inside the {% block content %} section changes.
Running the App
- Save base.html, home.html and about.html inside the templates folder.
- Run your Flask app using python app.py command.
- Open http://127.0.0.1:5000/ for the homepage and http://127.0.0.1:5000/about for the about page.
The home route displays the Home Page template:

The /about route displays the About Us page using the same base layout.

Explanation:
- Flask renders different templates based on the requested route.
- The shared structure from base.html is reused across all pages.
- Only the content inside {% block content %} changes for each template.