如何遍历 Jinja 模板中的字典列表? [英] How to iterate through a list of dictionaries in Jinja template?

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

问题描述

我试过了:

list1 = [{"username": "abhi", "pass": 2087}]return render_template("file_output.html", list1=list1)

在模板中:

<tr><td>钥匙</td><td>价值</td></tr>{% 用于 list1 中的字典 %}{% 用于字典中的键 %}<tr><td><h3>{{key }}</h3></td><td><h3>{{dictionary[key] }}</h3></td></tr>{% 结束为 %}{% 结束为 %}

上面的代码是将每个元素拆分成多个字符:

<预><代码>[{"你秒电子r...

我在一个简单的 Python 脚本中测试了上面的嵌套循环,它运行良好,但在 Jinja 模板中不起作用.

解决方案

数据:

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}}</h1><h2>值:{{value}}</h2>{% 结束为 %}{% 结束为 %}

注意:

确保你有字典项目的列表.如果你得到 UnicodeError 可能是 dict 里面的值包含 unicode 格式.这个问题可以在你的 views.py 中解决.如果dict是unicode对象,则必须编码成utf-8.

I tried:

list1 = [{"username": "abhi", "pass": 2087}]
return render_template("file_output.html", list1=list1)

In the template:

<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>

The above code is splitting each element into multiple characters:

[

{

"

u

s

e

r

...

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

解决方案

Data:

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

in Jinja2 iteration:

{% for dict_item in parent_list %}
   {% 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.

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

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