Sometimes in your template files, you might have some elements or features that are common to all of them. In this case, whenever you want to change the styling, or elements, you’ll have to do them manually by opening every template file and customizing them.
This is very time consuming and very difficult to maintain especially for large applications. Which is why a handy feature called Layout Inheritance is used.
This allows you to keep all the common elements inside one file(the parent template), and then the other template files inherit these elements from the new file you’ve created. That way whatever changes you make to the parent template gets inherited by all template files. This saves time and is easily maintenable.
for instance: you have 2 files, “index.html” and “about.html” and these two files share the same
code, styling and elements for the <head> part of the files.
You can create a parent template called “layout.html” and then store the <head> aspect of the
“index.html” and “about.html” files inside it. That way whatever changes is made to the
“layout.html” reflects in both template files. the parent template can look like this:
<!doctype html><html>
<head> {% block head %} <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> <title>{% block title %}{% endblock %} - My Webpage</title> {% endblock %}</head>
<body> <div id="content">{% block content %}{% endblock %}</div> <div id="footer"> {% block footer %} © Copyright 2010 by <a href="http://domain.invalid/">you</a>. {% endblock %} </div></body></html>NOTE: the {% block %} tags define four blocks that the child templates can fill in. All it does
is basically tell the template engine that a child template may override those portions of the
template. the “head” “title” “content” and “footer” that come after the “block” keyword are just
there to help make naming easier.
The child templates can look like this:
{% extends "layout.html" %}{% block title %}Index{% endblock %}{% block head %} {{ super() }} <style type="text/css"> .important { color: #336699; } </style>{% endblock %}{% block content %} <h1>Index</h1> <p class="important"> Welcome on my awesome homepage.{% endblock %}NOTE: The {% extends %} tag is the key here. It tells the template engine that this template
“extends” another template. When the template system evaluates this template, first it locates
the parent. The extends tag must be the first tag in the template. To render the contents of a
block defined in the parent template, use {{ super() }}