模板变量传递一直失败 没看出来问题在哪里

2016-07-27 15:16:26 +08:00
 Gescript
#python
from flask import Flask,render_template,request

app = Flask(__name__)

@app.route('/')
def index():
return render_template('index.html')

@app.route('/')
def User_Agent():
UserAgentString = request.headers.get('User-Agent')
return render_template('index.html', UserAgentString=UserAgentString)
if __name__ == '__main__':
app.run(debug=True)

#HTML

<!DOCTYPE html>
<html lang="en">
<head>
<title>Cololi's blog</title>
<link href="/static/css/bootstrap.min.css" rel="stylesheet">
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
</head>
<body background="/static/BGP.jpg">
<ul><li><strong>User-Agent: </strong>{{ User_AgentString }}</li></ul>
</body>
</html>
2688 次点击
所在节点    Flask
12 条回复
Gescript
2016-07-27 15:17:09 +08:00
debug 正常 HTTP 200
lxy
2016-07-27 15:19:53 +08:00
变量名没写对
Gescript
2016-07-27 15:23:10 +08:00
armoni
2016-07-27 15:23:23 +08:00
你页面里的变量是 User_AgentString , 你服务端的变量是 UserAgentString ,名字对不上
Gescript
2016-07-27 15:27:57 +08:00
Gescript
2016-07-27 15:28:38 +08:00
oroge
2016-07-27 15:34:11 +08:00
为什么有两个 @app.route ('/')?
Gescript
2016-07-27 15:36:35 +08:00
@oroge 忘记删掉了。。
cloverstd
2016-07-27 15:37:32 +08:00
你在 / 上绑定了俩个 view ,说明你访问的是第一个
Gescript
2016-07-27 15:43:10 +08:00
@cloverstd
@app.route('/')
def index():
return render_template('index.html')

def User_Agent():
UserAgentString = request.headers.get('User-Agent')
return render_template('index.html', UserAgentString=UserAgentString)
这样写也不行的样子一直不能在 html 上显示
cloverstd
2016-07-27 15:49:45 +08:00
@app.route('/')
def User_Agent():
UserAgentString = request.headers.get('User-Agent')
return render_template('index.html', UserAgentString=UserAgentString)
qq7171891
2016-07-28 09:47:20 +08:00
错误 1 :一个 @app.route('/') 不能绑定两个函数。
解决办法:可以用一个函数,里面加 if ,根据传入的参数加载不同逻辑。

错误 2 :变量名用错,后端传的是 UserAgentString ,前端又是 User_AgentString ,不一致。
解决办法:统一命名

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/295262

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX