template inheritance

 

The most powerful part of Jinja is its template inheritance feature, which allows you to create a basic skeleton template that contains common elements for your website and defines blocks that sub-templates can override .

It sounds complicated, but it's actually very basic. The best way to understand concepts is through examples.

basic template

A simple HTML document skeleton is defined in this template called layout.html , which you can use as a simple two-column page. And the child template is responsible for filling blank blocks:

 1 <!doctype html>
 2 <html>
 3   <head>
 4     {% block head %}
 5     <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
 6     <title>{% block title %}{% endblock %} - My Webpage</title>
 7     {% endblock %}
 8   </head>
 9 <body>
10   <div id="content">{% block content %}{% endblock %}</div>
11   <div id="footer">
12     {% block footer %}
13     © Copyright 2010 by <a href="http://domain.invalid/">you</a>.
14     {% endblock %}
15   </div>
16 </body>
View Code

 

In this example, the {% block %} tags are used to define four blocks that subtemplates can override. All the block tag does is tell the template engine that a child template may override this part of the parent template.

child template

The child template looks like this:

 1 {% extends "layout.html" %}
 2 {% block title %}Index{% endblock %}
 3 {% block head %}
 4   {{ super() }}
 5   <style type="text/css">
 6     .important { color: #336699; }
 7   </style>
 8 {% endblock %}
 9 {% block content %}
10   <h1>Index</h1>
11   <p class="important">
12     Welcome on my awesome homepage.
13 {% endblock %}
View Code

 

{% extends %} is the key to this example. It tells the template engine that this template inherits from another template. When the template engine analyzes this template, it will first locate its parent template. The extends tag must be the first tag of the template. To render a template in a parent template you need to use {{ super() }} .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325682897&siteId=291194637