django模板和列表字典

django模板和列表字典

本文介绍了django模板和列表字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

  example_dictionary = {key1:[value11,value12]} 

,我想执行以下操作:

  {%for example in example_dictionary% 
//这里的东西(1)
{%for example_dictionary.key%}
//更多的东西在这里(2)
{%endfor%}
{%endfor%}

但是,这不会在第二个for循环中输入。 >

的确,如果我把

  {{key}} 
(1)中的

,但是显示正确的键

  {{example_dictionary.key}} 

没有。



在中,有人提出使用



  {%for ke y,在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%}

示例:

  example_dictionary = {'a':[1,2]} 
{%for key,value_list in example_dictionary.items%}
打印键
{value_list%中的值%
打印值
{%endfor%}
{%endfor%}

结果将是:

 一个'
1
2

如果这不是你正在寻找请使用样本来挫败您的需求。


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

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

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.

Indeed, if I put

{{ key }}

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

{{ 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.

How do I achieve this? Am I missing something?

解决方案

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:

example_dictionary = {'a' : [1,2]}
{% for key, value_list  in example_dictionary.items %}
  print key
  {% for value in value_list %}
    print 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.

这篇关于django模板和列表字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 04:07