【问题标题】:Django template variables as key for a listDjango 模板变量作为列表的键
【发布时间】:2012-11-06 00:40:01
【问题描述】:

我来自这个问题Use variable as dictionary key in Django template

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

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

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

LIST1:
- a
- b
- c 

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

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

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

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

谢谢

【问题讨论】:

  • 使用{{ l[lv] }} 而不是{{ lv }} ?
  • 嗯,我认为我不能在模板中使用 []。反正我发现了问题。我需要用 () 而不是 {} 创建 touple

标签: django templates django-templates


【解决方案1】:

仅作记录,问题在于数据是如何创建的。所以而不是

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

我需要一个列表,所以:

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

【讨论】:

    【解决方案2】:

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

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

    这只是调用字典的iteritems 方法,该方法返回一个对2 元组列表的迭代器。

    Django's {% for %} tag documentation 也有一些很好的例子。

    【讨论】:

      猜你喜欢
      • 2021-07-23
      • 2016-08-26
      • 2018-06-05
      • 2016-04-05
      • 1970-01-01
      • 2012-07-22
      • 2023-03-19
      • 1970-01-01
      相关资源
      最近更新 更多