Django模板变量作为列表的关键

时间:2020-12-11 20:22:13

I'm coming from this question Use variable as dictionary key in Django template

我来自这个问题使用变量作为Django模板中的字典键

i've this context created in my view:

我在我的视图中创建了这个上下文:

{'cats': {'LIST1': ['a','b','c'], 'LIST2': ['aa','bb','cc','dd'], 'LIST3': ['f','g']}}

what i want to do is to print the list title and then all the items, something like

我想要做的是打印列表标题,然后打印所有项目,如

LIST1:
- a
- b
- c 

for all the lists, so i did this in my template

对于所有列表,所以我在我的模板中这样做了

{% for  l_name, l in cats %}
    {{ l_name }}

    {%for lv in l %}
        {{ lv }}
    {% endfor %}
{% endfor %}

and this prints only the list names, without printing out the list. where's the mistake?

这只打印列表名称,而不打印列表。哪里出错了?

thanks

2 个解决方案

#1


5  

If you want to iterate over keys and values, you can use:

如果要迭代键和值,可以使用:

{% for name, lst in cats.iteritems %}
.... 
{% endfor %}

This just calls the iteritems method of a dictionary, which returns an iterator over a list of 2-tuples.

这只是调用字典的iteritems方法,它在2元组列表上返回迭代器。

Django's {% for %} tag documentation has some nice example of this too.

Django的{%for%}标签文档也有一些很好的例子。

#2


0  

Just for the record, the problem is how the data are created. so instead of

仅供记录,问题在于如何创建数据。而不是

{'cats': {'LIST1': ['a','b','c'], 'LIST2': ['aa','bb','cc','dd'], 'LIST3': ['f','g']}}

i need a list of touple so:

我需要一个touple列表,所以:

{'cats': [('LIST1', ['a','b','c']), ('LIST2', ['aa','bb','cc','dd']), ('LIST3', ['f','g'])]}

#1


5  

If you want to iterate over keys and values, you can use:

如果要迭代键和值,可以使用:

{% for name, lst in cats.iteritems %}
.... 
{% endfor %}

This just calls the iteritems method of a dictionary, which returns an iterator over a list of 2-tuples.

这只是调用字典的iteritems方法,它在2元组列表上返回迭代器。

Django's {% for %} tag documentation has some nice example of this too.

Django的{%for%}标签文档也有一些很好的例子。

#2


0  

Just for the record, the problem is how the data are created. so instead of

仅供记录,问题在于如何创建数据。而不是

{'cats': {'LIST1': ['a','b','c'], 'LIST2': ['aa','bb','cc','dd'], 'LIST3': ['f','g']}}

i need a list of touple so:

我需要一个touple列表,所以:

{'cats': [('LIST1', ['a','b','c']), ('LIST2', ['aa','bb','cc','dd']), ('LIST3', ['f','g'])]}