【问题标题】:Django template and part of a dictionary of listsDjango 模板和列表字典的一部分
【发布时间】:2015-12-05 18:59:53
【问题描述】:

在 Django 中,我想在列表字典中显示一些条目。

我的上下文是:

keys = ['coins', 'colors']
dict = {'colors':['red', 'blue'],
        'animals':['dog','cat','bird'],
        'coins':['penny','nickel','dime','quarter'] } 

模板代码:

<ul>{% for k in keys %}
    <li>{{ k }}, {{ dict.k|length }}: [{% for v in dict.k %} {{ v }}, {% endfor %}]
{% endfor %}</ul>

我想看看:

* coins,4: [penny, nickel, dime, quarter,]
* colors,2: [red, blue,]

但我实际看到的是键但没有值:

* coins,0: []
* colors,0: []

注意:我也尝试了dict.{{k}} 而不是dict.k,但正如预期的那样,这只是在模板渲染中给出了解析错误。在基本列表正常工作后,我将用forloop.last 去掉结尾的逗号。

显示列表字典中选定值的秘诀是什么?

问题django template and dictionary of lists 显示整个字典,但我的要求是只显示可能非常大的字典中的几个条目。

【问题讨论】:

  • 本质上,Django 让在模板中使用dict 并以任何正常方式访问变得不必要的痛苦。你说得对,dict.k 查找不起作用,因为它正在寻找文字 k 属性而不是模板变量的值。对于这个用例,我建议您编写自己的自定义标签或过滤器来完成这项工作。

标签: python django dictionary django-templates


【解决方案1】:

问题(正如您所怀疑的)是 dict.k 被评估为 dict['k'] ,其中 'k' 不是字典中的有效键。尝试使用 dict.items 迭代每个项目对,并仅显示您关心的键的结果:

<ul>{% for k, v in dict.items %}
        {% if k in keys %}
            <li>
            {{ k }}, {{ v|length }}: [{% for val in v %} {{ val }},{% endfor %}]
           </li>
        {% endif %}
    {% endfor %}
</ul>

【讨论】:

  • items 还是iteritems
  • @ShangWang 物品,我的错。
  • 是的,感谢您证实了我的担忧。我希望避免仅仅为了显示一些条目而处理整个字典,但我猜 Django 模板不是那种 Python 的。看起来我必须重写views.py才能将一堆子集dicts传递给模板。
  • 另一种方法是编写一个简单的模板过滤器来进行动态查找:它是三行代码,请参阅this answer中的示例
【解决方案2】:
<ul>
    {% for k, v in dict.items %} # instead of iterating keys, iterate dict
        {% if k in keys %} # if key found in keys
            <li>
                {{ k }}, {{ v|length }}: [{% for val in v %} {{ val }},{% endfor %}]
            </li>
        {% endif %}
    {% endfor %}
</ul>

【讨论】:

    猜你喜欢
    • 2012-11-13
    • 2018-01-27
    • 2014-10-11
    • 1970-01-01
    • 2016-02-29
    • 2021-06-11
    • 2016-08-31
    • 2011-08-12
    • 2013-12-03
    相关资源
    最近更新 更多