Flask模板_给模板传入参数
一.模板传参的介绍
可以在python文件中的render_template中添加参数去传递,然后在模板中显示出所传参数的内容!
技巧:
如果你的参数项过多,那么可以将所有的参数放到一个字典 中, 然后在传这个字典参数的时候,使用两个星号,将字典打散成 关键字参数(也叫命名参数)
二.实例
html源码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>传参</title>
<style>
h2 {
color: aquamarine;
}
p {
color: burlywood;
}
</style>
</head>
<body>
<h2>哈哈~ {{ text1 }}</h2>
<hr style="color: red;">
<p>起飞!姓名:{{ uname }} 年龄:{{ uage }}</p>
<p>身高:{{ u.height }} 体重:{{ u['weight'] }} 兴趣:{{ u.get('love') }}</p>
</body>
</html>
python源码:
#coding=utf-8
from flask import Flask,render_template
app = Flask(__name__,template_folder='htmls')
@app.route('/')
def show_data():
data = {
'uname':'hh',
'uage':'20',
'u':{'height':'180cm','weight':'62kg','love':'Coding'}
}
return render_template('Flask模板_传参.html', **data, text1 = '此网页快被外星人抓走啦!')
if __name__ == '__main__':
app.run(debug=True)
注:
如果觉得笔记有些问题,麻烦在百忙之中在评论中指正,或提出建议!另外,如果觉得这份笔记对你有所帮助,麻烦动动发财的小手手点一波赞!