Implementation Method and Example of jinja2 Inheritance in Flask

  • 2021-09-16 07:18:38
  • OfStack

In the use of inheritance, we first came into contact with the inheritance of parent class and subclass. However, the inheritance in Flask framework is simpler. As long as there is an original file, it can be inherited and modified. In terms of modified content, it can be realized through keywords. Next, we introduce the theory of jinja2 inheritance in Flask, and then bring examples for everyone to practice.

1. Description

The most powerful part of Jinja2 is template inheritance. With template inheritance, we can create a basic (framework) file from which other files can be inherited, and then modify it as needed.

In the framework file of jinja2, the block keyword is used to indicate that its contents can be modified.

2. Examples


<!DOCTYPE html>
<html>
<head>
  {% block head %}
  <link rel="stylesheet" href="style.css" rel="external nofollow" />
  <title>{% block title %}{% endblock %} - My Webpage</title>
  {% endblock %}
</head>
<body>
<div id="content">{% block content %}{% endblock %}</div>
<div id="footer">
  {% block footer %}
  <script>This is javascript code </script>
  {% endblock %}
</div>
</body>
</html>

Here, four block are defined, namely, head, title, content and footer. Then how to inherit and replace variables? Pay attention to the following files


{% extend "base.html" %}    #  Inheritance base.html Documents 
{% block title %} Dachenzi {% endblock %}  #  Customize title Part of the content 
{% block head %}
{
{ super() }}    #  Used to get the original information 
<style type='text/css'>
.important { color: #FFFFFF }
</style>
{% endblock %}  
#  Other intact and different inheritance without modification 

Instance extension:

jinja2 template inheritance

Father:


<!DOCTYPE html>
<html>
<head>
 <title> Template inheritance </title>
</head>
<body>
 <span> This is the base template </span>
 <div id="content">{% block content %}{% endblock %}</div>
</body>
</html>

Font plate containing jinja2 with {% block content%} {% endblock%};

Child:


<!DOCTYPE html>
<html>
<head>
 <title> Template inheritance </title>
</head>
<body>
 {% extend "jinja2_ Template inheritance .html"%}
 {% block content %}
 <p class="importtant"> I am in the sub-template </p>
</body>
</html>

The {% extends "jinja2_ Template Inheritance. html"%} tag is the key here, telling the template engine that this template inherits from another template. This tag must be the first tag of the child template, and the interpreter will automatically copy the parent's content to the child template!

The result should be this:


<!DOCTYPE html>
<html>
<head>
 <title> Template inheritance </title>
</head>
<body>
 <span> This is the base template </span>
 <div id="content">
   <p class="importtant"> I am in the sub-template </p>
  </div>
</body>
</html>


Related articles: