Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through dictionary passed from Python/Tornado handler to Tornado's template?

Tags:

python

tornado

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}}
like image 312
PaolaJ. Avatar asked Jun 17 '13 13:06

PaolaJ.


2 Answers

>>> 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>
like image 119
falsetru Avatar answered Oct 24 '22 01:10

falsetru


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>
like image 42
Parison Avatar answered Oct 23 '22 23:10

Parison