无法在 Flask 中的 html 标签内使用 url_for 转到另一个页面

我无法about_me从index页面转到页面。错误 :


在服务器上找不到请求的 URL。


并得到像"http://127.0.0.1:5000/%7B%7B%20url_for('about')%20%7D%7D".


from flask import Flask, redirect, url_for

app = 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) 


侃侃尔雅
浏览 605回答 1
1回答

ibeautiful

您用于插入关于我页面的 url_for 的格式,即:<a href={{url_for('about_me')}}">about</a>只能在 Jinja 模板中工作。在返回响应之前,模板引擎会处理这些模板,并且在处理过程中,带有两个大括号的符号{{ something }}会被识别并以不同的方式解释。但是,在这里,您没有在 Jinja 模板中使用此表示法,而是在普通字符串中使用它,该字符串不会被处理,因此不会被替换。在这种情况下,实现您想要的正确方法是参数化字符串并通过格式传递链接。例如:@app.route('/')def index():&nbsp; &nbsp; return '''&nbsp; &nbsp; <!DOCTYPE html><html><head>&nbsp; &nbsp; <title>Title</title></head><body>&nbsp; &nbsp; <p>welcome home</p>&nbsp; &nbsp; <a href="{about_me}">about</a>&nbsp; &nbsp; </body></html>'''.format(about_me=url_for('about_me'))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python