Template Inheritance in Flask (original) (raw)
Last Updated : 9 Jun, 2026
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.
Python `
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
HTML `
My Flask AppWelcome to My Website
{% block content %}{% endblock %}`
**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
Python `
{% extends "base.html" %}
{% block content %}
Home Page
Welcome to the homepage of our Flask app!
{% 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
Python `
{% extends "base.html" %}
{% block content %}
About Us
This is the about page of our Flask app.
{% 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:

Snapshot of Home Page
The /about route displays the About Us page using the same base layout.

Snapshot of About Us page
**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.