Django_template inheritance

Template inheritance first creates a parent template, which contains common elements for most pages, and needs to define blocks tags that can be overridden by child templates.

extends template inheritance

Use the following example to understand the concept of template inheritance.

Create a base.html file and write the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>{% block title %}基础模板{% endblock %}</title>
</head>

<body>
    <div id="app">
        <!-- 如果是所有页面共用部分,可直接在block外部写死 -->
        <div> 所有页面公用部分 </div>
        <!-- 如果是部分页面共用部分,可定义在block中,不需要使用的页面可重写该block,其中block_name1为block的名称 -->
        {% block block_name1 %}
            <div> 部分页面公用部分1 </div>
        {% endblock %}
        {% block block_name2 %}
            <div> 部分页面公用部分2 </div>
        {% endblock %}
        <!-- 定义的block可以为空白块 -->
        {% block block_name3 %}
        {% endblock %}
    </div>
</body>
</html>

Inherit the bse.html template directly in the child template.

Create a demo.html file and write the following code:

<!-- 继承base.html模板 -->
{% extends "base.html" %}

Write a view function to call the demo.html template above, and then visit the page

You can see that the child template displays all the content of the parent template.

rewrite block 

Modify the content of the demo.html file as follows:

<!-- 继承base.html模板 -->
{% extends "base.html" %}

<!-- 重写tile的block -->
{% block title%} Demo {% endblock %}

<!-- 重写block_name1的block---重写内容 -->
{% block block_name1 %} 重写部分页面公用部分1 {% endblock %}

<!-- 重写block_name2的block---隐藏内容 -->
{% block block_name2 %}{% endblock %}

<!-- 重写block_name3的block---重写内容 -->
{% block block_name3 %}
    <div> hello python!</div>
    <div> 你好,python! </div>
{% endblock %}

Access the demo.html template, the displayed content is as follows:

Subtemplates can also be overridden by inheritance

Modify the content of the demo.html file as follows:

<!-- 继承base.html模板 -->
{% extends "base.html" %}

<!-- 重写tile的block -->
{% block title%} Demo {% endblock %}

<!-- 重写block_name1的block---重写内容 -->
{% block block_name1 %} 重写部分页面公用部分1 {% endblock %}

<!-- 重写block_name2的block---隐藏内容 -->
{% block block_name2 %}{% endblock %}

<!-- 重写block_name3的block---重写内容 -->
{% block block_name3 %}
    <div> hello python!</div>
    <div> 你好,python! </div>
    {% block block_name4 %}
    {% endblock %}
{% endblock %}

The content of the newly added demo1.html file is as follows:

<!-- 继承demo.html模板 -->
{% extends "demo.html" %}

{% block title%} Demo1 {% endblock %}

{% block block_name4 %}
<div>继承子模板</div>
{% endblock %}

Visit demo1.html, the displayed content is as follows:


Source code and other data acquisition methods

 Friends who want to get the source code, please like + comment + favorite , triple!

After three times in a row , I will send you private messages one by one in the comment area~

 

Guess you like

Origin blog.csdn.net/GDYY3721/article/details/131637418