Flask(5)-Jinja2模板使用(传参)
-
传参方式一
# app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/index/")
def index():
# 传递参数username,必须是关键字参数
return render_template("index.html", username="hahahahah")
if __name__ == '__main__':
app.run(debug=True)
<!-- index.html-->
<!DOCTYPE html>
<html lang="zh-en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>index</title>
</head>
<body>
<h1>Index</h1>
<!--接收传递的参数-->
<h1>{
{ username }}</h1>
</body>
</html>
-
传参方式二
# app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/index/")
def index():
res = {
"username": "hahahaha",
"age": 20
}
# return render_template("index.html", res = res) 模板里调用{
{res.username}}
return render_template("index.html", **res)
if __name__ == '__main__':
app.run(debug=True)
<!-- index.html -->
<!DOCTYPE html>
<html lang="zh-en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>index</title>
</head>
<body>
<h1>Index</h1>
<!-- <h1>{
{ res.username }}</h1> 后端传参方式 return render_template("index.html", res=res)-->
<h1>{
{ username }}</h1>
</body>
</html>
正文到此结束
评论
登录后才能发表评论 登录/注册
0评论