1. 简单示例
1.1. 父模板 base.html
<!DOCTYPE html><html lang="en"><head><link rel="stylesheet" href="style.css" /><title>{% block title %}My amazing site{% endblock %}</title></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 %}</div></body></html>
1.2. 子模板 example.html
{% extends "base.html" %}{% block title %}My amazing blog{% endblock %}{% block content %}{% for entry in blog_entries %}<h2>{{ entry.title }}</h2><p>{{ entry.body }}</p>{% endfor %}{% endblock %}
注意
- {% extends %} 标签告诉模板引擎继承了哪个模板
- 子模板中没有定义的部分将继承父模板内容
2. 多级继承
2.1. 步骤
- 创建
base.html控制整站视觉及体验 - app 中
a. 创建base_SECTION.html比如base_news.html
b. 继承命名空间/base.html同时又自有样式 - 创建页面独立模板,继承对应 app 的模板
2.2. 说明
{% extends %}必须是第一个标签,必须在首行{% block %}
a. 在 base.html 中越多越好
b. 如果有大量内容重复,都应该放到其中- 如果用到父模板中内容用
{{ block.super }}
