Jinja 表达式中的引用模板变量 [英] Reference template variable within Jinja expression

查看:20
本文介绍了Jinja 表达式中的引用模板变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样定义的路线:

I have a route defined like this:

@app.route('/magic/<filename>')
def moremagic(filename):
    pass

现在在模板中,我想使用 url_for() 调用该路由,如下所示:

And now in a template I want to call that route using url_for() like so:

<h1>you uploaded {{ name }}<h1>
<a href="{{ url_for('/magic/<filename>') }}">Click to see magic happen</a>

我试过了:

<a href="{{ url_for('/magic', filename={{ name }}) }}">Click to see magic happen</a>

这会抛出一个 jinja2.TemplateSyntaxError: expected token ':' got }

任何人都可以建议如何将出现在模板中的 {{ name }} 放入 url_for() 以便当我点击时调用正确的 >app.route?

Can anyone suggest how to get the {{ name }} that appears in the template into the url_for() so that when I click I call the correct app.route?

推荐答案

{{ ... }} 中的所有内容都是类似 Python 的表达式.您不需要在其中使用另一个 {{ ... }} 来引用变量.

Everything inside the {{ ... }} is a Python-like expression. You don't need to use another {{ ... }} inside that to reference variables.

去掉多余的括号:

<h1>you uploaded {{ name }}<h1>
<a href="{{ url_for('moremagic', filename=name) }}">Click to see magic happen</a>

(注意,url_for() 函数采用端点 name,而不是 URL 路径;名称默认为函数的名称,moremagic 在你的例子中).

(Note that the url_for() function takes the endpoint name, not a URL path; the name defaults to the name of the function, moremagic in your example).

这篇关于Jinja 表达式中的引用模板变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆