1.0 模板
1.1 介绍
模板是WEB开发必备的模块,我们在渲染网页时,并不只是渲染一个纯文本字符串,而是渲染一个富文本的页面,这时候我们就需要模板,在flask中配套的模板是jinja2,jinja2的作者也是flask的作者。
1.2 flask渲染jinja2模板
要渲染一个模块,使用render_template方法
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/boot/')
def hello():
return render_template('demo.html') #对demo页面进行渲染
if __name__ == '__main__':
app.run(debug=True)
讲解:
hello函数会在指定的templates文件夹中寻找demo.html模板文件,如果需要更改模板文件地址,则需要给Flask传递一个关键字参数template_folder=“新模板文件地址”
1.3 模板文件传参
render_template 中需要传两个参数
- 1.需要渲染的模块名
- 2.关键字参数,如下:
#主文件
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/')
def her():
#return render_template('aaa.html',username='逻辑教育',age = 1810 )
# 通过render_template来渲染index模块
cotest = {
'username':'luoji','age' : 18,'books' : {
'henge': 1, 'time':15}}
return render_template('aaa.html',**cotest)
if __name__ == '__main__':
app.run(debug