学习笔记,仅供参考
参考自:Django打造大型企业官网–Huang Y;
本系列Blog以应用为主,理论基础部分我在后端专栏的Django系列博客已经写过了,如果有些需要补充的知识点,我会在这个系列中,尽量详细的记录一下。
include模板标签
理论
有时候一些代码是在许多模版中是可以复用的,一般我们可以把这些重复性的代码抽取出来,就类似于Python中的函数一样,以后想要使用这些代码的时候,就通过include
导入进来,例如:
# header.html
<p>我是header</p>
# footer.html
<p>我是footer</p>
# main.html
{% include 'header.html' %}
<p>我是main内容</p>
{% include 'footer.html' %}
include
标签寻找路径的方式,和render
函数寻找模板路径的方式是一样的。
include
标签包含的模版,会自动的使用主模版中的变量,如果想传入一些其他的参数到include
标签包含的模板中,那么可以使用with
语句:
# header.html
<p>用户名:{{ username }}</p>
# main.html
{% include "header.html" with username='huangyong' %}
实践
- 创建模板
首先,我们在templates文件夹下创建4个模板文件header.html, footer.html, index.html, bookstore.html:
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% include 'header.html' %}
<div class="content">
这是中间内容{{ username }}
</div>
{% include 'footer.html' %}
</body>
</html>
bookstore:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% include 'header.html' with username='Bai' %}
<div class="content">
这是书店的内容
</div>
{% include 'footer.html' %}
</body>
</html>
header.html:
<header>
<ul>
<li><a href="/">首页</a></li>
<li><a href="{% url 'bookstore' %}">书店</a></li>
<li>{{ username }}</li>
</ul>
</header>
footer.html:
<footer>
这是footer部分
</footer>
- 发起请求
向http://127.0.0.1:8000/发起请求:
点击书店: