How to iterate through dictionary passed from Python/Tornado handler to Tornado's template ?
I tried like
<div id="statistics-table">
{% for key, value in statistics %}
{{key}} : {{value['number']}}
{% end %}
</div>
but it doesn't work, where statistics is dictionary
statistics = { 1 : {'number' : 2}, 2 : {'number' : 8}}
>>> 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>
Alternative:
<div id="statistics-table">
{% for key in statistics %}
{{key}} : {{statistics[key]['number']}}
{% end %}
</div>
Here is another way you can do it :
//Let's suppose dico is the dictionary object you passed as a parameter in the handler's render method
{% 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With