小编典典

如何迭代Jinja模板中的词典列表?

flask

我试过了:

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>

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

[

{

"

u

s

e

r

...

我在一个简单的Python脚本中测试了上述嵌套循环,但效果很好,但在Jinja模板中却无法正常工作。


阅读 481

收藏
2020-04-05

共1个答案

小编典典

数据:

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

在Jinja2迭代中:

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

注意:
确保你有字典项列表。如果得到的UnicodeError可能是字典中的值包含unicode格式。views.py 如果你的字典是unicode对象,则可以解决该问题,你必须将其编码为utf-8

2020-04-05