如何遍历从Python / Tornado处理程序传递到Tornado模板的字典?
我试过
<div id="statistics-table">
{% for key, value in statistics %}
{{key}} : {{value['number']}}
{% end %}
</div>
但它不起作用,统计数据是字典
statistics = { 1 : {'number' : 2}, 2 : {'number' : 8}}
答案 0 :(得分:10)
>>> 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>
答案 1 :(得分:1)
以下是另一种方法:
//假设dico是您在处理程序的渲染方法中作为参数传递的字典对象
{% 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>