Template Inheritance in Flask

·

3 min read

Table of contents

No heading

No headings in the article.

What is template inheritance? A web application has a minimum of four to five pages. These pages contain common components like header, footer, background, etc. So, these components collectively put into a template for reusability.

Other pages of the application inherit these templates, hence the process is called template inheritance. Let's see how we can do the same in Flask.

Every webpage has a header specifically a navigation bar and a footer displaying the business's objective and important hyperlinks to different services.

Let's say we have a directory structure that looks like the following:

flask_project/
|- app.py
|- templates
    |- base_layout.html
    |- about.html
    |- product.html
|- static

We need to create a Flask app to serve our templates. Add the following code into the app.py file.

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def home():
    return render_template("base_layout.html")

@app.route("/about")
def about():
    return render_template("about.html")

@app.route("/products")
def products():
    return render_template("product.html")

if __name__ == "__main__":
    app.run(debug=True)

We have three templates that will be rendered on their respective URLs that's why we created three routes (/, /about, and /products) in our app.

Here's a simple navbar and footer using Bootstrap.

<!-- base_layout.html -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Template Inheritance</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<!-- Navbar -->
<nav class="navbar navbar-expand-lg bg-info">
    <div class="container-fluid">
        <a class="navbar-brand" href="#">Navbar</a>
        <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
            <div class="navbar-nav">
                <a class="nav-link active" aria-current="page" href="#">Home</a>
                <a class="nav-link" href="#">Products</a>
                <a class="nav-link" href="#">About</a>
            </div>
        </div>
    </div>
</nav>

<!-- Main Content of Page -->
{% block content %}
<h1> This is Homepage </h1>
{% endblock %}

<!-- Footer -->
<footer class="bg-dark text-white">
    <div class="container py-4">
        <div class="row">
            <p class="mb-0">© 2024 Your Company. All rights reserved.</p>
        </div>
    </div>
</footer>
</body>
</html>

Now run the app and go to this URL http://127.0.0.1:5000.

base_layout webpage

Our webpage now has a simple layout. The next goal is to avoid explicitly including the identical components (navbar and footer) on each page (about.html and product.html).

As a result, we will use base_layout.html as our base template to include the navbar and footer on subsequent web pages.

How'll we do that? Of course, by using template inheritance. Let's start things off.

Here, we'll use Jinja syntax to achieve our goal. In the about.html add the following code.

<!-- about.html -->

<!-- Base template layout -->
{% extends 'base_layout.html' %}

<!-- Main Content of Page -->
{% block content %}
<h1> This is About Page </h1>
{% endblock %}

This line ({% extends 'base_layout.html' %}) indicates that the about.html template will use the base_layout.html template as its base. This means that about.html inherits the structure and layout defined in base_layout.html.

If you've noticed, we inserted the content block ({% block content %}{% endblock %}) in our base template, which will help us serve the dynamic content. This is what we've done after extending the base layout.

Now, we can insert anything within the content block using the above syntax, in this case, we've inserted a simple <h1> tag.

This is the result we got, about.html serving on http://127.0.0.1:5000/about.

About page using base layout

Similarly, we can do this in product.html as well.

<!-- product.html -->

<!-- Base template layout -->
{% extends 'base_layout.html' %}

<!-- Main Content of Page -->
{% block content %}
<h1> This is Product Page </h1>
{% endblock %}

This time we are serving different content. Here's the result.

Product page using base layout


🏆Other articles you might be interested in if you liked this one

Type hints in Python - Callable objects, Return values, and more?

Best Practices: Positional and Keyword Arguments in Python

Yield Keyword in Python with Examples?

Create a WebSocket Server and Client in Python.

Create and Interact with MySQL Database in Python.

Understanding the use of global keyword in Python.


That's all for now

Keep Coding✌✌

Did you find this article valuable?

Support Team - GeekPython by becoming a sponsor. Any amount is appreciated!