我可以在Flask模板中嵌套变量吗? [英] Can I nest variables in Flask templates?

查看:47
本文介绍了我可以在Flask模板中嵌套变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个人,我在Flask中遇到了一个问题.mysql中有一个名为category的表,我查询了所有表,然后将它们传递给a.html,如下所示:

everyone, i met a problem in Flask. There is a table in mysql named category, I queried all of them, then passed them to a.html, like this :

return render_template('admin_index.html', username=session.get('username'), categories=categories)

在admin_index.html中,我想列出所有这些,这是我的代码:

In admin_index.html, I wanna list all of them, here is my code:

var _menus = {
    "menus": [
        {
            "menuid": "1",
            "icon": "icon-sys",
            "menuname": "category",
            "menus": [
                {% for category in categories %}
                    {
                        "menuid": "{{ category.id }}",
                        "menuname":"{{ category.name }}",
                        "icon": "icon-users",
                        "url": "{{url_for('admin.category', id={{category.id}} _external=True) }}"
                    },
                {% endfor %}
            ]
        }
    ]
};

但是当我运行它时,我得到了一个错误:

but when i ran this, i got an error:

jinja2.exceptions.TemplateSyntaxError:预期令牌':',得到了'}'

jinja2.exceptions.TemplateSyntaxError: expected token ':', got '}'

我尝试删除{{category.id}},结果很好,我怀疑不允许在Flask模板中嵌套变量,例如:

I tried remove {{ category.id }}, turned out OK, I suspect it's not allowed to nest variables in Flask template, which like this :

{{ a is {{ b }} }}

有什么办法可以嵌套它?

Is there any way i can nest it?

推荐答案

您已经在jinja表达式中.因此,将执行以下代码:

You are already inside a jinja expression. So the following code is executed:

url_for("admin.category", id={{category.id}} _external=True)

由于 {,它需要一个字典,因此会出现错误.

Because of the { it expects a dictionary hence the error.

要使用 category.id 的值,只需省略大括号:

To use the value of category.id simply omit the curly brackets:

url_for("admin.category", id=category.id, _external=True)

还请注意,您忘记了"_external"之前的 .

Also note that you forgot a , before "_external".

这篇关于我可以在Flask模板中嵌套变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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