如何迭代Jinja模板中的词典列表?
发布于 2021-01-29 17:55:07
我试过了:
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模板中却无法正常工作。
关注者
0
被浏览
47
1 个回答
-
数据:
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
object,则必须编码为utf-8
。