我正在尝试使用 flask 的 url_for() 通过向用户传递用户名来导航到用户页面。我有 html 文件作为
{% for user in users %}
<li><h2>{{ user.name }}</h2>{{ user.email|safe }}
<a href="{{ url_for('users_stats',username = {{ user.name }}) }}">stats</a> #This doesn't work
<a href="/users/{{ user.name }}"> stats </a> #This does work
在我的 python 文件中,我的函数为
@app.route('/users/<username>')
def users_stats(username):
...
我在其中渲染另一个模板。为什么第一种方法不起作用?另外,由于第二种方法有效,通常的做法是像那样做 url 还是使用 url_for()?
请您参考如下方法:
取而代之的是:
<a href="{{ url_for('users_stats',username = {{ user.name }}) }}">stats</a>
这样做:
<a href="{{ url_for('users_stats',username = user.name) }}">stats</a>
您已经在 {{ 和 }} block 中,因此您不需要添加第二层。
