1、什么是模板
模板是一个web开发必备的模块。因为我们在渲染一个网页的时候,并不是只渲染一个纯文本字符串,而是需要渲染一个有富文本标签的页面。
这时候我们就需要使用模板了。在Flask中,配套的模板是Jinja2,Jinja2的作者也是Flask的作者。这个模板非常的强大,并且执行效率高。以下对Jinja2做一个简单介绍!
2、flask渲染jinja2模板(render_template)
1、第一步,在当前路径创建templates文件夹
注意点:
1、默认名字是templates(专门用于存放模板文件),如果书写错误,则会报错
2、如果在template文件夹中写入另一个文件夹则需要写出相对应的路径(如在templates文件夹中,创建了 profile文件夹用于存放index.html文件,则在导入是应该写成:
return render_template(“profile/index.html”)
2、第二步,在templates文件夹中,书写相关需要渲染的页面、模板(如创建index.html)
3、第三步,通过render_template()导入(index.html)
相关步骤呈现:
第一步、第二步
第三步:
import flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def home():
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
呈现效果:
更改templates文件夹(一般不会进行更改)
# 1、通过绝对路径更换,可以适应不同的盘符
from flask import Flask, render_template
app = Flask(__name__, template_folder=r"C:\Users\asus\Desktop\flask练习\dome")
@app.route("/")
def home():
return "首页"
@app.route("/index/")
def index():
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
# 1、在当前路径下进行修改,适应性较差
from flask import Flask, render_template
app = Flask(__name__, template_folder=r"./dome")
@app.route("/")
def home():
return "首页"
@app.route("/index/")
def index():
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
3、模板传参
1、一个简单的例子(传入单个参数):
代码部分:
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def home():
return "首页"
@app.route("/index/")
def index():
return render_template("index.html", name="流浪者、j")
if __name__ == "__main__":
app.run(debug=True)
模板接收参数:{{ xxx }}
返回结果:
2、传入多个参数
# 比较直接的方式
@app.route("/index/")
def index():
return render_template("index.html", name="流浪者、j", home="兰溪", age=18)
通过字典完成传参
1、方法一
代码部分
context = {
"name":"流浪者、j",
"home":"兰溪",
"age":18
}
@app.route("/index/")
def index():
return render_template("index.html", context=context)
# 改变了上述传参方式导致代码臃肿的问题
模板部分(context["name"] or context.name)<br /><br /> 最终结果<br /><br />虽然通过这种方式使代码在呈现上更加优雅,但是却也导致了模板部分的书写困难,于是进行改进<br />** 2、方法二(将context=context 改为 **context)**<br />** 代码部分**
context = {
"name":"流浪者、j",
"home":"兰溪",
"age":18
}
@app.route("/index/")
def index():
return render_template("index.html", **context)
# 这种方式就对context进行转化,变为了name="流浪者、j", home="兰溪", age=18的形式
模板部分<br /><br /> 最终结果<br />
4、嵌套取值(context中嵌套了字典或者列表)
嵌套字典
context = {
"name":"流浪者、j",
"home":"兰溪",
"age":18
books = {"book1":"python"
"book2":"java"}
}
取出python
# 写法一
{{ books.book1 }}
# 写法二
{{ books['book1'] }}
嵌套列表,索引取值
context = {
"name":"流浪者、j",
"home":"兰溪",
"age":18
books = ["python", "java", "php"]
}
取出python,如果索引越界不报错,只是不显示
# 写法一
{{ books.0}}
# 写法二
{{ books[0] }}
5、模板中的注释
1、注释方法一:ctrl + / ( <!-- <h2>{{ age }}</h2> --> )<br /><br /> 注释的并不是非常完全,在运行时还有可能干扰程序的正常运行<br /> 2、通过{# {{ age }} #}的方式进行注释<br />