5

如何遍历从 Python/Tornado 处理程序传递到 Tornado 模板的字典?

我试过了

    <div id="statistics-table">
            {% for key, value in statistics %}
            {{key}} : {{value['number']}}
            {% end %}
        </div>

但它不起作用,统计数据是字典

statistics = { 1 : {'number' : 2},  2 : {'number' : 8}}
4

2 回答 2

12
>>> from tornado import template
>>> t = template.Template('''
... <div id="statistics-table">
...     {% for key, value in statistics.items() %}
...     {{key}} : {{value['number']}}
...     {% end %}
... </div>
... ''')
>>> statistics = { 1 : {'number' : 2},  2 : {'number' : 8}}
>>> print(t.generate(statistics=statistics))

<div id="statistics-table">

    1 : 2

    2 : 8

</div>

选择:

<div id="statistics-table">
    {% for key in statistics %}
    {{key}} : {{statistics[key]['number']}}
    {% end %}
</div>
于 2013-06-17T13:48:11.617 回答
1

这是另一种方法:

//假设dico是您在处理程序的render方法中作为参数传递的字典对象

{% autoescape None %}
<script>

var dict={{ json_encode(dico) }};  
//Now,just iterate over dict which is a javascript associative array
for (k in dict)
{
console.log("dico["+k+"] = "+dico[k]);
}

</script>
于 2015-08-10T12:48:12.903 回答