1、include语句
最主要的作用是复用代码,可以将一个模板引入到另一个模板中,也就是完成”将一个模板中的代码复制到另一个模板中”的功能
小例子,现在有html1.html以及html2.html两个模板文件需要共用一部分的共用代码
代码部分
from flask import Flask, render_templateapp = Flask(__name__)app.config["TEMPLATES_AUTO_RELOAD"] = True@app.route("/")def home():return "首页"@app.route("/html1/")def html1():return render_template("html1.html")@app.route("/html2/")def html2():return render_template("html2.html")if __name__ == "__main__":app.run(debug=True)
模板部分:在templates文件夹中创建commit文件夹用来存放共有代码部分footer.html以及header.html文件
footer.html
<footer>这是网页底部</footer>
header.html
<ul><li>新闻</li><li>电视</li><li>综艺</li></ul>
在新的模板中引入这些公有的模板
html1.html
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>html1</title></head><body>{% include 'commit/header.html' %}<h1>昨日青空</h1>{% include 'commit/footer.html' %}</body></html>
html2.html
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>html2</title></head><body>{% include 'commit/header.html' %}<h1>流浪地球</h1>{% include 'commit/footer.html' %}</body></html>
2、set语句以及with语句
- set语句相当于在当前模板中定义了一个全局变量,(但在py文件中有同名的变量时,优先使用set定义的变量)
- with语句相当于在当前模板中定义了一个局部变量,作用范围从{% with %}开始到{% endwith %}结束
- 变量的种类可以是数字、字符、字典、列表等等
代码部分:
from flask import Flask, render_templateapp = Flask(__name__)app.config["TEMPLATES_AUTO_RELOAD"] = Truedic = {"name": "python","books": {"book1": "python","book2": "java","book3": "php"}}@app.route("/")def home():return "首页"@app.route("/set/")def set_html():return render_template("set.html", **dic)if __name__ == "__main__":app.run(debug=True)
模板部分:(有部分可以定义宏,但是我懒哈哈)
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>set</title></head><body><!--set相当于定义一个全局变量-->{% set name="这是set定义的变量" %}<p>{{ name }}</p><hr><!--with相当于定义一个局部变量,不要忘了endwith-->{% with books={"book1": "红楼梦", "book2": "三国演义", "book3": "西游记" }%}{% for book in books.values() %}<p>{{ book }}</p>{% endfor %}{% endwith %}<hr><!--with定义的变量在这里失效了--><!--此时调用的是py文件中传入的参数-->{% for book in books.values() %}<p>{{ book }}</p>{% endfor %}<hr><!--变量的赋值可以是从py文件中导入-->{% with books=books%}{% for book in books.values() %}<p>{{ book }}</p>{% endfor %}{% endwith %}</body></html>
页面显示:
总结三种定义方式:
<!--第一种-->{% set xxx=xxx %}<!--第二种-->{% with %}{% set xxx=xxx %}xxxx{% endwith %}<!--第三种-->{% with xxx=xxx %}xxxx{% endwith %}

