简体   繁体   English

Django模板和列表字典的一部分

[英]Django template and part of a dictionary of lists

in Django I want to display some entries in a dictionary of lists. 在Django中,我想在列表字典中显示一些条目。

My context is: 我的上下文是:

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

Template code: 模板代码:

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

I want to see: 我想看看:

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

But what I actually see is keys but no values: 但是我实际上看到的是键,但没有值:

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

Note: I also tried dict.{{k}} instead of dict.k , but as expected that just gave a parse error in template rendering. 注意:我也尝试了dict.{{k}}而不是dict.k ,但是正如所期望的那样,这只是在模板渲染中产生了解析错误。 I'll get rid of the trailing comma with forloop.last after getting the basic list working. 在基本列表正常运行后,我将使用forloop.last删除尾随的逗号。

What is the secret sauce for displaying selected values from a dictionary of lists? 显示列表字典中选定值的秘诀是什么?

The question django template and dictionary of lists displays an entire dictionary, but my requirement is to display only a few entries from a potentially very large dictionary. 问题django模板和列表字典显示整个字典,但是我的要求是仅显示可能很大的字典中的少数条目。

The problem (as you suspected) is that dict.k is evaluated to dict['k'] where 'k' is not a valid key in the dictionary. 问题(您怀疑)是dict.k被评估为dict ['k'],其中'k'在字典中不是有效键。 Try instead to iterate each item pair using dict.items and only display the results for the keys you're concerned with: 而是尝试使用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>
<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM