我无法about_me从index页面转到页面。错误 :在服务器上找不到请求的 URL。并得到像"http://127.0.0.1:5000/%7B%7B%20url_for('about')%20%7D%7D".from flask import Flask, redirect, url_forapp = Flask(__name__)@app.route('/')def index(): return ''' <!DOCTYPE html><html><head> <title>Title</title></head><body><p>welcome home</p><a href="{{ url_for('about_me') }}">about</a></body></html>'''@app.route('/about')def about_me(): return 'about me'if __name__ == '__main__': app.run(debug=True)
1 回答

ibeautiful
TA贡献1993条经验 获得超5个赞
您用于插入关于我页面的 url_for 的格式,即:
<a href={{url_for('about_me')}}">about</a>
只能在 Jinja 模板中工作。在返回响应之前,模板引擎会处理这些模板,并且在处理过程中,带有两个大括号的符号{{ something }}会被识别并以不同的方式解释。
但是,在这里,您没有在 Jinja 模板中使用此表示法,而是在普通字符串中使用它,该字符串不会被处理,因此不会被替换。
在这种情况下,实现您想要的正确方法是参数化字符串并通过格式传递链接。例如:
@app.route('/')
def index():
return '''
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>
<p>welcome home</p>
<a href="{about_me}">about</a>
</body>
</html>
'''.format(about_me=url_for('about_me'))
添加回答
举报
0/150
提交
取消