如何遍历Jinja模板中的词典列表? [英] How to iterate through a list of dictionaries in Jinja template?

查看:126
本文介绍了如何遍历Jinja模板中的词典列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过:

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

在模板中:

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

上面的代码将每个元素分成多个字符:

The above code is splitting each element into multiple characters:

[

{

"

u

s

e

r

...

我在一个简单的Python脚本中测试了上述嵌套循环,并且可以在Jinja模板中正常运行.

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

推荐答案

数据:

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

在Jinja2迭代中:

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

注意:

确保您具有词典项目列表.如果得到UnicodeError,则dict中的值可能包含unicode格式.该问题可以在您的views.py中解决. 如果dict是unicode对象,则必须编码为utf-8.

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.

这篇关于如何遍历Jinja模板中的词典列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆