use*_*927 53 python iteration dictionary jinja2 flask
我试过了
list1 = [{"username": "abhi", "pass": 2087}]
return render_template("file_output.html", list1=list1)
Run Code Online (Sandbox Code Playgroud)
在模板中
<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>
Run Code Online (Sandbox Code Playgroud)
上面的代码将每个元素分成多个
核心价值 [
{
"
ü
小号
e ...
我在一个简单的python脚本中测试了上面的嵌套循环,它工作正常,但不是在jinja模板中.
Nav*_*ava 120
parent_dict = [{'A':'val1','B':'val2'},{'C':'val3','D':'val4'}]
Run Code Online (Sandbox Code Playgroud)
{% for dict_item in parent_dict %}
{% for key, value in dict_item.items() %}
<h1>Key: {{key}}</h1>
<h2>Value: {{value}}</h2>
{% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
确保你有dict项目列表.如果你得到UnicodeError可能是dict里面的值包含unicode格式.这个问题可以在你views.py
的dict是unicode对象的情况下解决,你必须编码utf-8
Chr*_*s.Q 15
作为@Navaneethan回答的旁注,Jinja2能够为列表和字典做"常规"项目选择,因为我们知道字典的键,或列表中项目的位置.
parent_dict = [{'A':'val1','B':'val2', 'content': [["1.1", "2.2"]]},{'A':'val3','B':'val4', 'content': [["3.3", "4.4"]]}]
Run Code Online (Sandbox Code Playgroud)
{% 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 %}
Run Code Online (Sandbox Code Playgroud)
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.
Run Code Online (Sandbox Code Playgroud)
{% for i in yourlist %}
{% for k,v in i.items() %}
{# do what you want here #}
{% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
128059 次 |
| 最近记录: |