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:

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 App

Welcome to My Website

{% block content %}{% endblock %}

`

**Explanation:

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:

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:

Running the App

  1. Save base.html, home.html and about.html inside the templates folder.
  2. Run your Flask app using **python app.py command.
  3. 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:

home-page

Snapshot of Home Page

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

about-us

Snapshot of About Us page

**Explanation: