检索Jinja字典值

3

I have a python Dictionary that looks like this

[{"hat": 91, "d1b": 2, "d1c": 1, "d1d": 5, "d1e": 7, "d1f": 77, "d1e": 999}
{"hat": 1, "d2b": 2, "d2c": 3, "d2d": 4, "d2e": 5, "d2f": 6, "d2e": 7}
{"hat": 1, "d3b": 2, "d3c": 3, "d3d": 4, "d3e": 5, "d3f": 6, "d3e": 7}]

我将这个作为字典对象(mydict)从Python传递给Jinja。

我的目标是循环遍历每个字典,并打印出我搜索的键的值。并在jQuery警告框中显示它。

$(document).ready(function() {

        {% for i in mydict %}
          {{ loop.index0 }}, {{a,["hat"] }}
               alert( {{ hat }} );
            {% endfor %}
        });

当我访问我的网页时,出现了错误提示:
Uncaught SyntaxError: Unexpected token &

$(document).ready(function() {


          0, (Undefined, [[hat[])
               alert(  );

          1, (Undefined, [hat])
               alert(  );

          2, (Undefined, [hat])
               alert(  );

        });

它没有被定义,也没有输出警报。

1个回答

7
你需要像Python一样使用call来处理字典(它不是集合):
{% for i in dict %}
    {{ i['hat'] }}
{% endfor %}

集合可以被视为字典来访问,而字典不能被称为集合。无论如何,如果这是一个集合,您需要使用 i.hat,如果这是一个集合或字典,则需要使用 i['hats']

尝试替换它:

alert( {{ hat }} );

to:

alert( {{ i['hat'] }} );

抱歉,这是一个集合,我忘记放在原始帖子中了,请查看编辑。 - jumpman8947
我很高兴能够帮助。 - JRazor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接