VOOZH about

URL: https://www.geeksforgeeks.org/python/template-inheritance-in-flask/

⇱ Template Inheritance in Flask - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Template Inheritance in Flask

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.

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

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

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

Explanation:

  • about.html reuses the same layout from base.html.
  • Only the content inside the {% block content %} section changes.

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:

  • 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.
Comment
Article Tags: