通过从下面这个例子,可以容易的理解模版继承:
base.html模板:它定义了一个简单HTML骨架。“子模版”的工作是“填充空的或者覆盖“ base.html里的blocks。
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css" />
<title>{% block title %}My amazing site{% endblock %}</title> -------设置默认内容(My amazing site)
</head>
<body>
<div id="sidebar">
{% block sidebar %}
<ul>
<li><a href="/">Home</a></li>
<li><a href="/blog/">Blog</a></li>
</ul>
{% endblock %}
</div>
<div id="content">
{% block content %}{% endblock %} -------为block设置名字:content
</div>
</body>
</html>
注意:
如果你在模版中使用 {% extends %} 标签,它必须是模版中的第一个标签。其他的任何情况下,模版继承都将无法工作。
{{ block.super content}} -------保留继承下来的内容,然后追加你的内容
子模版:
在这个例子中, block
标签定义了三个可以被子模版内容填充的block。 block
告诉模版引擎:
子模版可能会覆盖掉模版中的这些位置。
{% extends "base.html" %} ----------继承base.html模板所有内容
{% block title %}My amazing blog{% endblock %}----(My amazing blog)覆盖base.html(My amazing site)
{% block content %}
{% for entry in blog_entries %}
<h2>{{ entry.title }}</h2>
<p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
子模版经过渲染后是这样的:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css" />
<title>My amazing blog</title>-------修改后
</head>
<body>
<div id="sidebar">-------继承下来的内容
<ul>
<li><a href="/">Home</a></li>
<li><a href="/blog/">Blog</a></li>
</ul>
</div>
<div id="content">-------修改后
<h2>Entry one</h2>
<p>This is my first entry.</p>
<h2>Entry two</h2>
<p>This is my second entry.</p>
</div>
</body>
</html>