我试过了:
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模板中就不行了。
发布于 2014-08-19 12:46:34
数据:
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
,里面的值可能是unicode格式的。这个问题可以在你的views.py
中解决。如果dict是unicode
对象,你必须编码成utf-8
。
发布于 2015-09-11 05:10:05
作为@Navaneethan答案的附注,Jinja2
能够对列表和字典进行“常规”条目选择,前提是我们知道字典的关键字或条目在列表中的位置。
数据:
parent_dict = [{'A':'val1','B':'val2', 'content': [["1.1", "2.2"]]},{'A':'val3','B':'val4', 'content': [["3.3", "4.4"]]}]
在Jinja2迭代中:
{% 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 %}
渲染的输出:
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.
发布于 2014-08-19 06:48:20
{% for i in yourlist %}
{% for k,v in i.items() %}
{# do what you want here #}
{% endfor %}
{% endfor %}
https://stackoverflow.com/questions/25373154
复制相似问题