【问题标题】:Using keys() on django template在 django 模板上使用 keys()
【发布时间】:2012-08-19 21:03:35
【问题描述】:

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

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

response['dict'] = {'a': [1,2,4], 'b': [5,6,7]}

在 html 中,我尝试使用键进行循环

{% if dict %}
  {% for list in dict.keys() %}
    list
  {% endfor %}
{endif}

这是抛出一个错误。

TemplateSyntaxError: 无法解析余数:'keys()' from 'dict.keys()

在这里需要帮助。如何在 Django 中使用它?

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

    这可能是因为dict是Python中的保留关键字。试试

    {% if d %}
      {% for key in d.keys() %}
        list
      {% endfor %}
    {endif}
    

    或者干脆

    {% if d %}
      {% for key in d %}
        list
      {% endfor %}
    {endif}
    

    默认情况下,python 中字典上的迭代器是键上的,因此您不必指定您想要键而不是 .items() 或 .values()。

    【讨论】:

    • 使用 d.keys() 不正确 - 模板中不能使用括号,正确的符号是 d.keys
    • dict 不是保留关键字,它是内置类型的名称。如果你真的想的话,Python 实际上并不会阻止你重新分配名称 dict,尽管不可否认,这不是一个好主意,因为你会失去对内置函数的访问权限。
    • dict 是一个不错的选择,但我只是在这里使用它。对困惑感到抱歉。 yedpodtrzitko 的回答解决了这个问题。谢谢
    • @redrah 我看不出它是如何减少保留的。 Python 不会阻止您覆盖它这一事实使它作为指向内置字典的名称保留得同样少。
    • @MattiLyra 我知道你从哪里来,但我的意思是关键字和名称之间有一个重要的区别。例如class、if 等是 Python 中的关键字,因此不可能给变量命名为 class,因为它是为语法保留的,如果你尝试你会得到一个 SyntaxError。名称除了作为名称之外没有语法重要性,因此任何名称都可以分配给任何对象,甚至是dict。
    【解决方案2】:
    {% if dict %}
      {% for key, value in dict.items %}
        list
      {% endfor %}
    {endif}
    

    编辑:

    {% if dict %} 不需要 - 如果给定上下文的变量为空(或者如果它是空字典),它会静默通过:

      {% for key, value in dict.items %}
        list
      {% endfor %}
    

    【讨论】:

    • 是的,这里的重点——正如文档中清楚解释的那样——是你不要在 Django 模板中使用调用 ()。
    • 在相关说明中。如何在 django 中使用 join {% for key, value in dict.items %} ('\n').join(list) ???? {% endfor %}
    猜你喜欢
    • 2013-09-15
    • 2015-09-07
    • 2018-11-25
    • 2016-01-20
    • 2018-03-22
    • 2011-09-11
    • 2018-11-03
    • 2018-01-09
    • 1970-01-01
    相关资源
    最近更新 更多