django模板和列表字典
我使用的是django的模板系统,存在以下问题: 我将dictionary对象example\u dictionary传递给模板:django模板和列表字典,django,django-templates,Django,Django Templates,我使用的是django的模板系统,存在以下问题: 我将dictionary对象example\u dictionary传递给模板: example_dictionary = {key1 : [value11,value12]} 我想做以下几点: {% for key in example_dictionary %} // stuff here (1) {% for value in example_dictionary.key %} // more stuff here (2) {% endf
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)上,它显示正确的键,但是
{{ example_dictionary.key }}
什么也看不出来
年,有人提议使用
{% for key, value in example_dictionary.items %}
但是,这在本例中不起作用,因为我希望(1)获得有关特定密钥的信息
我如何做到这一点?我遗漏了什么吗?我猜您正在寻找嵌套循环。在外部循环中,您使用字典键执行某些操作,在嵌套循环中,您迭代iterable字典值,即案例中的列表 在这种情况下,这是您需要的控制流:
{% for key, value_list in example_dictionary.items %}
# stuff here (1)
{% for value in value_list %}
# more stuff here (2)
{% endfor %}
{% endfor %}
样本:
#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
如果这不是你正在寻找的,请用一个样本来说明你的需求