Template Inheritance in Flask
Template inheritance is a powerful feature in Jinja, the templating engine used in Flask. It allows us to define a common structure for web pages, such as headers, footers, and navigation bars, in a base template. This prevents redundant code and makes managing multiple pages easier.
Prerequisite - Flask – (Creating first simple application)
Features of Template Inheritance
- Code Reusability: Write common HTML structure once and reuse it across multiple pages.
- Better Maintainability: Updating the base template updates all inherited templates automatically.
- Separation of Concerns: Keeps the structure and content of web pages separate for better organization.
- Scalability: Easily add new pages without duplicating code.
Implementing Template Inheritance
Step 1: Set Up a Flask App
Create a basic Flask application that renders an HTML template.
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)
Step 2: Create a Base Template
The base.html file contains the common structure for all web pages. The {% block content %} {% endblock %} section is where unique content for each page will go.
<!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>
Step 3: Create Child Templates
Now, let's create home.html and about.html, which inherit from base.html using {% extends "base.html" %}. The {% block content %} section contains unique content for each page.
home.html
{% extends "base.html" %}
{% block content %}
<h2>Home Page</h2>
<p>Welcome to the homepage of our Flask app!</p>
{% endblock %}
about.html
{% extends "base.html" %}
{% block content %}
<h2>About Us</h2>
<p>This is the about page of our Flask app.</p>
{% endblock %}
Running the Application
- 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.
Below is the snapshot of the app in development server.


Working:
- When you visit different routes (/, /about, /contact), Flask dynamically renders the appropriate template.
- The common structure from base.html is reused.
- The {% block content %} placeholder is replaced with each page’s specific content.
- This ensures a consistent layout across multiple pages.