django 模板和列表字典

标签 django django-templates

我正在使用 django 的模板系统,但遇到以下问题:

我将字典对象 example_dictionary 传递给模板:

example_dictionary = {key1 : [value11,value12]}

我想做以下事情:
{% for key in example_dictionary %}
// stuff here (1)
{% for value in example_dictionary.key %}
// more stuff here (2)
{% endfor %}
{% endfor %}

但是,这不会进入第二个 for 循环。

确实,如果我把
{{ key }}

在 (1) 上,它显示了正确的 key ,但是,
{{ example_dictionary.key }}

什么都不显示。

this answer ,有人提议使用
{% for key, value in example_dictionary.items %}

但是,这在这种情况下不起作用,因为我希望 (1) 获得有关特定键的信息。

我如何实现这一目标?我错过了什么吗?

最佳答案

我假设您正在寻找嵌套循环。在外部循环中,您使用字典键执行某些操作,并且在嵌套循环中,您迭代可迭代字典值,即您的案例中的列表。
在这种情况下,这是您需要的控制流:

{% for key, value_list  in example_dictionary.items %}
  # stuff here (1)
  {% for value in value_list %}
    # more stuff here (2)
  {% endfor %}
{% endfor %}
一个 sample :
#view to template ctx:
example_dictionary = {'a' : [1,2]}

#template:
{% for key, value_list  in example_dictionary.items %}
  The key is {{key}}
  {% for value in value_list %}
    The key is {{key}} and the value is {{value}}
  {% endfor %}
{% endfor %}
结果将是:
The key is a
The key is a and the value is 1
The key is a and the value is 2
如果这不是您要找的,请使用示例来说明您的需求。

关于django 模板和列表字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13561009/

相关文章:

python - 使用Django服务 protected 媒体文件

python - Nodeenv 抛出 python virtualenv 不可用

python - 如何在 Web 服务器中设置 Python?

Django - 模板标签中的 verbose_name

django - 在 Django 模板中,firstof 还是 default?

python - Django 单元测试随机失败

javascript - 返回 QuerySet.values() 或 value_list() 中方法的结果?

django-admin - 如何仅为 1 个应用程序覆盖 django edit_inline/tabular.html?

django - 当表单无效时, View 未返回 HttpResponse 对象错误 : django

python - Django 无效 block 标记 : 'endfor' , 预期 'endblock'