How to iterate through a list of dictionaries in Jinja template?

后端 未结 5 1369
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 20:00

I tried:

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

In the template:

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 20:22

    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.
    

提交回复
热议问题