How to iterate over a dictionary through a Python / Tornado transmitter to a Tornado template?

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

I tried both

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

but it doesnโ€™t work, where statistics is a dictionary

 statistics = { 1 : {'number' : 2}, 2 : {'number' : 8}} 
+4
source share
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> 
+10
source

Here is another way to do this:

// Suppose dico is the dictionary that you passed as a parameter in the handler's rendering 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> 
+1
source

Source: https://habr.com/ru/post/1486623/


All Articles