django eight-django template inheritance (block and extends)

I. Introduction

The role of django template inheritance: Templates can be reused by inheritance to reduce redundant content.

Generally speaking, there are generally multiple pages in a website whose head and tail content are consistent, and we can achieve reuse through template inheritance.

The parent template is used to place reusable content, and the child template inherits the content of the parent template and places its own content.

Second, the parent template

Label block...endblock:  The reserved area in the parent template. This area is reserved for sub-templates to fill with different content. The names of different reserved areas cannot be the same.

{% block 名称1 %} 

The area reserved for sub-templates, you can set the default content

{% endblock 名称1 %}

{% block 名称2 %} 

The area reserved for sub-templates, you can set the default content

{% endblock 名称2 %}

Three, sub-template

The child template uses the tag extends to inherit the parent template:

{% extends "父模板路径"%}

If the child template does not set the content of the reserved area of ​​the parent template, the default content set in the parent template is used. Of course, it is not necessary to set it, and it will be empty.

The child template sets the content of the reserved area of ​​the parent template:

{ % block 名称 % }

content 

{% endblock 名称 %}

Fourth, the debugging process

1. Next, we add a [base_001.html] file in [helloworld/hello/templates] of the django project [helloworld], the code is as follows:

There can be from 0 to an infinite number of block tags with different names in a parent template. 

In the above code, the block tag named mainbody and the block tag named subbody are parts that can be replaced by the successors.

All {% block %} tags tell the template engine that sub-templates can override these parts.

2. Next, we add a [xiaolei_001.html] file in [helloworld/hello/templates] of the django project [helloworld], the code is as follows:

We can see that xiaolei.html inherits base_001.html and replaces the content in a specific block.

The first line of code description: the child template xiaolei.html inherits the parent template base_001.html.

can be seen:

(1). The content of the block tag named [mainbody] in the sub-template xiaolei.html is used to replace the content of the block tag with the same name as [mainbody] in the parent template base_001.html.

(2) The content in the block tag named [subbody] in the parent template base_001.html is directly displayed by the child template xiaolei.html.

3. Write a corresponding new view function [xiaolei] and a new url matching rule [url(r"^xiaolei001/$", views.xiaolei)].

4. Start the django project [helloworld], and then enter the address [http://127.0.0.1:8000/xiaolei001/] in any browser, you can see the correct display result:

Guess you like

Origin blog.csdn.net/LYX_WIN/article/details/114268249