How to iterate through a list of dictionaries in j

2019-01-17 05:52发布

问题:

I tried

list1 = [{"username": "abhi", "pass": 2087}]
return render_template("file_output.html",lis=list1)

in the template

<table border=2>    
<tr>
<td>    
    Key
</td>   
<td>
    Value
</td>
</tr>
{% for lis1 in lis %}
{% for key in lis1 %}   
<tr>
<td>
    <h3>{{key}}</h3>
</td>
<td>
    <h3>{{lis1[key]}}</h3>
</td>
</tr>
{% endfor %}
{% endfor %}
</table>

The above code is splitting each element into multiple

Key Value [

{

"

u

s

e ...

I tested the above nested loop in a simple python script and it works fine but not in jinja template.

回答1:

Data:

parent_dict = [{'A':'val1','B':'val2'},{'C':'val3','D':'val4'}]

in Jinja2 iteration:

{% for dict_item in parent_dict %}
   {% for key, value in dict_item.items() %}
      <h1>Key: {{key}}</h1>
      <h2>Value: {{value}}</h2>
   {% endfor %}
{% endfor %}

Note:

make sure you have the list of dict items.If you get UnicodeError may be the value inside the dict contains unicode format. That issue can be solved in your views.py if the dict is unicode object, you have to encode into utf-8



回答2:

As a sidenote to @Navaneethan 's answer, Jinja2 is able to do "regular" item selections for the list and the dictionary, given we know the key of the dictionary, or the locations of items in the list.

Data:

parent_dict = [{'A':'val1','B':'val2', 'content': [["1.1", "2.2"]]},{'A':'val3','B':'val4', 'content': [["3.3", "4.4"]]}]

in Jinja2 iteration:

{% for dict_item in parent_dict %}
   This example has {{dict_item['A']}} and {{dict_item['B']}}:
       with the content --
       {% for item in dict_item['content'] %}{{item[0]}} and {{item[1]}}{% endfor %}.
{% endfor %}

The rendered output:

This example has val1 and val2:
    with the content --
    1.1 and 2.2.

This example has val3 and val4:
   with the content --
   3.3 and 4.4.


回答3:

{% for i in yourlist %}
  {% for k,v in i.items() %}
    {# do what you want here #}
  {% endfor %}
{% endfor %}