You are currently viewing Template Inheritance in Flask with Example

Template Inheritance in Flask with Example

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:

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

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.

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

Base Layout

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.

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, this 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.

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✌✌