忍者模板中的字典列表 [英] list of dictionary in jinja template

查看:119
本文介绍了忍者模板中的字典列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何遍历jinja模板中的字典列表?

  list1 = [{username:abhi,pass:2087}] 

在模板中返回render_template(file_output.html,lis = list1)



 < table border = 2> 
< tr>
< td>
Key
< / td>
< td>
价值
< / td>
< / tr>
{%for lis1 in lis%}
{%for key in lis1%}
< tr>
< td>
< h3> {{key}}< / h3>
< / td>
< td>
< h3> {{lis1 [key]}}< / h3>
< / td>
< / tr>
{%endfor%}
{%endfor%}
< / table>

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

关键值
[b / b]

{b / b>








...



我在一个简单的python脚本中测试了上面的嵌套循环,并且工作正常,但是在jinja模板中没有。

解决方案数据:

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



< h3>在Jinja2迭代中:

$ p $ {$ c $ {$%for dict_item in parent_dict%}
{%for key,dict_item .items()%}
< h1>密钥:{{key}}< / h1>
< h2>值:{{value}}< / h2>
{%endfor%}
{%endfor%}



注意:



确保你有dict items的列表。如果你得到 UnicodeError 可能是这个问题可以在你的 views.py
中解决,如果字典是 unicode 对象,你必须编码到 utf-8


How to iterate through the list of dictionaries in jinja template?

list1=[{"username": "abhi","pass": 2087}]

 return render_template("file_output.html",lis=list1)

in the template

<table border=2>    
<tr>
<td>    
    Key
</td>   
<td>
    Value
</td>
</tr>
{% for lis1 in lis %}
{% for key in lis1 %}   
<tr>
<td>
    <h3>{{key}}</h3>
</td>
<td>
    <h3>{{lis1[key]}}</h3>
</td>
</tr>
{% endfor %}
{% endfor %}
</table>

The above code is splitting each element into multiple

Key Value [

{

"

u

s

e ...

I tested the above nested loop in a simple python script and it works fine but not in jinja template.

解决方案

Data:

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

in Jinja2 iteration:

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

Note:

make sure you have the list of dict items.If you get UnicodeError may be the value inside the dict contains unicode format. That issue can be solved in your views.py if the dict is unicode object, you have to encode into utf-8

这篇关于忍者模板中的字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆