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

新手上路,请多包涵

我试过了:

 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 许可协议

阅读 2.2k
2 个回答

数据:

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

笔记:

确保你有 dict 项目的列表。如果您得到 UnicodeError 可能是 dict 内的值包含 unicode 格式。该问题可以在您的 views.py 中解决。如果 dict 是 unicode 对象,则必须编码为 utf-8

原文由 Nava 发布,翻译遵循 CC BY-SA 4.0 许可协议

作为@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.

原文由 Chris.Q 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题