# Template Inheritance in Flask

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:

```python
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.

```python
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.

```xml
<!-- 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1722517100555/85fd7bfa-bff7-4f14-863c-5b72d7726743.png align="center")

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.

```xml
<!-- 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1722519720405/4bcfd648-200f-40af-b691-e4c90792c7ec.png align="center")

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

```xml
<!-- 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1722519891594/82e37761-7bf1-4268-be8b-29ab828660fe.png align="center")

---

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

✅[Type hints in Python - Callable objects, Return values, and more](https://geekpython.in/type-hinting-in-python)?

✅[Best Practices: Positional and Keyword Arguments in Python](https://geekpython.in/positional-and-keyword-arguments-in-python)

✅[Yield Keyword in Python with Examples](https://geekpython.in/yield-keyword-in-python)?

✅[Create a WebSocket Server and Client in Python](https://geekpython.in/build-websocket-server-and-client-using-python).

✅[Create and Interact with MySQL Database in Python](https://geekpython.in/mysql-database-in-python).

✅[Understanding the use of global keyword in Python](https://geekpython.in/understanding-the-use-of-global-keyword-in-python).

---

**That's all for now**

**Keep Coding✌✌**
