Python Friday #35: Shared Layouts in Jinja

Our web application will be a maintenance nightmare when all our pages contain the full layout of our site. Luckily for us, Jinja offers a simple solution for this problem called template inheritance.

This post is part of my journey to learn Python. You can find the other parts of this series here.

 

The problem

If all our templates contain the whole layout of our web site, then a small change means we need to update all templates. Even for small applications this is error prone and takes a lot of time.

A much better approach is to have a base layout with navigation and everything and then only the minimal content needed for a site in the site-specific template. In this case we need only update one file when we need a new entry in the navigation.

 

The starting template for tasks

As the example for this post I will use this HTML file (tasks.html) that contains all the data to display tasks as I build it up in the last post:

 

Create a base template

To reuse our current HTML, we got to our template folder and copy the tasks.html template to the file base.html:

Jinja has the concept of blocks, where we can specify a part of our HTML template that other pages can override. A block looks like this and needs a name, like footer in this example:

It does not matter if the block is empty or contains data. We can decide later on if the other pages should override what is there or keep the content as it is.

We now need to go through the base.html template and replace all the task specific parts with blocks. I did this and created a block for the page title and one for the main content:

 

Use the base template

We now modify the tasks.html file to use our template. We can have multiple base templates; therefore, we must tell Jinja which one we want to use. The mechanism we use is called template inheritance and we now make tasks.html a child page of our base template (called base.html):

For every block we want to override, we write a snipped like this one:

That is all we need to do. If we repeat this for the main block and get rid of everything else in the tasks.html file, we end up with this:

 

What do we gain?

It will take time until the benefits for maintaining our application start to pile up. But as soon as we add another page we can profit from our template. To create an “About” site, we only need these few lines:

With our base.html template this is all it takes to give us a site with a navigation bar and the whole Bootstrap layout:

The About site gets the whole layout including the navigation bar

 

Next

Base templates in combination with the basics of Jinja allows us to create nice layouts for our web applications. It is now time to look a bit closer on the routing in Flask to move away from static sites.

1 thought on “Python Friday #35: Shared Layouts in Jinja”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.