django模板和列表字典

时间:2021-03-03 14:31:15

I'm using django's template system, and I'm having the following problem:

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

I pass a dictionary object, example_dictionary, to the template:

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

example_dictionary = {key1 : [value11,value12]}

and I want to do the following:

我想做以下事情:

{% for key in example_dictionary %}
// stuff here (1)
{% for value in example_dictionary.key %}
// more stuff here (2)
{% endfor %}
{% endfor %}

However, this does not enter on the second for loop.

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

Indeed, if I put

的确,如果我放

{{ key }}

on the (1), it shows the correct key, however,

在(1)上,它显示正确的键,但是,

{{ example_dictionary.key }}

shows nothing.

In this answer, someone proposed using

在这个答案中,有人建议使用

{% for key, value in example_dictionary.items %}

However, this does not work in this case because I want (1) to have information regarding the particular key.

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

How do I achieve this? Am I missing something?

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

1 个解决方案

#1


11  

I supose that you are looking for a nested loop. In external loop you do something with dictionary key and, in nested loop, you iterate over iterable dictionary value, a list in your case.

我想你正在寻找一个嵌套循环。在外部循环中,您使用字典键执行某些操作,并在嵌套循环中迭代可迭代字典值,即您的案例中的列表。

In this case, this is the control flow that you need:

在这种情况下,这是您需要的控制流程:

{% for key, value_list  in example_dictionary.items %}
  # stuff here (1)
  {% for value in value_list %}
    # more stuff here (2)
  {% endfor %}
{% endfor %}

A 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 %}

Results will be:

结果将是:

'a'
1
2

If this is not that you are looking for, please, use a sample to ilustrate your needs.

如果这不是您要找的,请使用样品来说明您的需求。

#1


11  

I supose that you are looking for a nested loop. In external loop you do something with dictionary key and, in nested loop, you iterate over iterable dictionary value, a list in your case.

我想你正在寻找一个嵌套循环。在外部循环中,您使用字典键执行某些操作,并在嵌套循环中迭代可迭代字典值,即您的案例中的列表。

In this case, this is the control flow that you need:

在这种情况下,这是您需要的控制流程:

{% for key, value_list  in example_dictionary.items %}
  # stuff here (1)
  {% for value in value_list %}
    # more stuff here (2)
  {% endfor %}
{% endfor %}

A 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 %}

Results will be:

结果将是:

'a'
1
2

If this is not that you are looking for, please, use a sample to ilustrate your needs.

如果这不是您要找的,请使用样品来说明您的需求。