Subject: Flask: Python Web Development
Looking at the previous lesson and the ones related to the School Grading System you must have noticed some annoying repitition of code in the templates html files
This code is supposed to be a layout with navigations that appears on all the HTML templates files, but as we introduced more HTML files, if we need to make a change to the navigation link for example, we will have to do this across several of this files which is a very bad practice that can turn to a nightmare to maintain as the code base of project grows.
Fortunately, jinja supports template inheritance, allowing the creation of a base or layout template that you can extend in other or child templates, encouraging code reuse and a consistent layout across different pages of out project.
Create a base or layout template Create a new template named layout.html in a templates folder:
templates/layout.html
School Grading System - {% block title %}{% endblock title %}
School Grading System
{% block subheading %}{% endblock subheading %}
{% block content %}
No messages.
{% endblock content %}
Some styling to beautify our web app Notice this line in the layout.html
This mean that I have added a CSS style file to the static folder which is now refrenced by the layout and as such all the templates that will extend our layout with the beautifully styled.
Base or layout template is designed to provide a consistent structure for your project while allowing flexibility in specific parts of the content through Jinja’s block functionality.
Extend the base or layout template Now create child templates to extend the base or layout, in this example I modified our three views template to extend layout.html and fill in these blocks with their specific content.
templates/index.html
{% extends 'layout.html' %}
{% block title %}Welcome{% endblock title %}
Note: The vhild templates also contain {% block %} tags. By providing the block’s name as an argument, you’re connecting the blocks from the child template with the blocks from the base or layout template.
Now you can run the app.py and see the result on the web browser