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.
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:
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:
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):
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:
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.