include和set语句
include语句
flask中的include语句可以将一个模板的代码复制到另一个模板中,以实现代码的复用
include语句格式
{% include 'HTML/samepart/header.html' %}
<!-- include后面加一个文件路径(相对于templates) -->
复用代码1(header.html)
<ul>
<li>学院首页</li>
<li>教师队伍</li>
<li>学科建设</li>
</ul>
复用代码2(footer.html)
<div class="footer">
页面底部
</div>
这两个复用代码,都放在一个文件夹里(templates下的HTML下的samepart)
接着在另一个html文件中写include语句
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>教师队伍</title>
</head>
<body>
<!--include将另外一个页面的代码复制到该页面,实现代码的复用-->
{% include 'HTML/samepart/header.html' %}
<h2>教师队伍页面</h2>
{% include 'HTML/samepart/footer.html' %}
</body>
</html>
这样这个html文件就已经复用了header.html和footer.html里的代码
set语句
flask中set语句是赋值语句,可以将变量添加到模板中
set语句格式
{% set username='Snow' %}
<!-- set后面是变量名和变量值 -->
如果在body下使用set,那么进行赋值的该变量就是一个全局变量,下面如果使用传参的方式传递参数,传递的参数可能会被该全局变量覆盖。
如果不想设置的变量覆盖后面传递的参数,可以用with语句
with语句格式
{% with ... %}
{% endwith %}
用with语句包裹变量的方式:
- 在with里面使用set语句
{% with %} <!-- 如果不想在全局设置变量以防污染到别的数据,可以通过with来框起一个局部作用域,然后在里面用set语句即可 -->
{% set sex='女' %}
<h3>性别:{{ sex }}</h3>
{% endwith %}
- 在with后设置变量
{% with age=18 %} <!-- 还可以在with里设置变量,该变量还可以是字符串,也可以是序列 -->
<h3>年龄:{{ age }}</h3>
{% endwith %}
with后面的变量还可以是列表,字典等序列
{% with dict={'name': 'Sleet', 'sex': 'male'} %}
{% for key in dict.keys() %}
<p>{{ dict[key] }}</p>
{% endfor %}
{% endwith %}
{% with lst = [1,2,3] %}
{% for i in lst %}
<p>{{ i }}</p>
{% endfor %}
{% endwith %}
由于with结构里的变量是局部变量,所以如果拿到with外面在无法用