我试过了:
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 模板中却不行。
原文由 user3089927 发布,翻译遵循 CC BY-SA 4.0 许可协议
数据:
在 Jinja2 迭代中:
笔记:
确保你有 dict 项目的列表。如果您得到
UnicodeError
可能是 dict 内的值包含 unicode 格式。该问题可以在您的views.py
中解决。如果 dict 是unicode
对象,则必须编码为utf-8
。