在django模板上使用keys()

Rav*_*eja 1 python django django-templates

这是一个使用dict.keys()的快速问题

我在py文件中返回一个字典Ex:

response['dict'] = {'a': [1,2,4], 'b': [5,6,7]}
Run Code Online (Sandbox Code Playgroud)

在html中我试着使用键循环

{% if dict %}
  {% for list in dict.keys() %}
    list
  {% endfor %}
{endif}
Run Code Online (Sandbox Code Playgroud)

这是一个错误.

TemplateSyntaxError:无法解析余数:来自'dict.keys()的'keys()'

需要帮助.如何在Django中使用它?

yed*_*tko 5

{% if dict %}
  {% for key, value in dict.items %}
    list
  {% endfor %}
{endif}
Run Code Online (Sandbox Code Playgroud)

编辑:

{% if dict %} 不需要 - 如果给定上下文的变量是空的(或者如果它是空的dict),它默默地传递:

  {% for key, value in dict.items %}
    list
  {% endfor %}
Run Code Online (Sandbox Code Playgroud)

  • 是的,这里的要点 - 正如文档中清楚解释的那样 - 是你不在Django模板中使用调用`()`. (2认同)