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

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)

在Jinja2迭代中:

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

  • 可能是因为我正在使用更新版本的jinja,但在我的情况下我必须删除括号(改为使用`dict_item.items`)或者它会抛出一个`无法解析余数:'()'来自' dict_item.items()'` (11认同)
  • @TrakJohnson:那么您**不使用Jinja模板**,而是使用* Django *模板。您想阅读[如何在Django模板的字典中迭代字典?](// stackoverflow.com/q/8018973)。Django模板语法相似,但不相同。 (5认同)
  • @CameronHyde:Jinja在所有版本中都支持对所有对象的属性和项目访问。请参阅模板文档的[* Variables *]部分](http://jinja.pocoo.org/docs/2.10/templates/#variables)。如果`dict [“ key”]`不适用于您,则说明您使用的不是Jinja模板,而是Django模板。请参阅[通过Django模板中的键访问字典](// stackoverflow.com/q/19745091) (3认同)
  • 除了 TrakJohnson 的回答之外,我还发现新的 jinja 使用 `dict.key` 而不是传统的 `dict["key"]` 来索引字典。 (2认同)

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)

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


cor*_*vid 8

{% for i in yourlist %}
  {% for k,v in i.items() %}
    {# do what you want here #}
  {% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

  • @user3089927 您的模板是否比您向我们展示的更多?这个解决方案是正确的。如果不是,则执行您共享的代码时,“lis”不是列表。 (2认同)