【问题标题】:django template access multiple dictionaries within loopsdjango模板在循环中访问多个字典
【发布时间】:2013-12-03 20:47:59
【问题描述】:

我有两本词典

dictlist = {'Red': {345: 25.0, 123: 67.0, 678: 0, 777: 0}, 'Yellow': {345: 20, 123: 10, 678: 10, 777: 10}, 'Blue': {345: 25.0, 123: 67.0, 678: 0, 777: 0}

dict1 = {345: 4, 123: 4, 678: 3, 777: 1}

我想要一个包含每种颜色的模板: 代码/百分比(来自 dictlist)/总计(来自 dict1)

到目前为止,我得到了:

    {% for key, val in dictlist.items %}
<h2>{{ key }}</h2>
<table>
    <tr>
        <td>Code</td>
        <td>Percentage</td>
    </tr>

        {% for k,v in val.items %}
        <tr>
            <td>{{ k }}</td>
            <td>{{ v }}</td>
            {% for k in dict1.items %}
            <td>{{ dict1.items.k }}</td>
            {% endfor %}
        </tr>
        {% endfor %}
</table>

我无法从 dictlist for 循环内的 dict1 访问匹配的键...我还能如何访问循环内的不同字典?

提前致谢

【问题讨论】:

    标签: django dictionary django-templates


    【解决方案1】:

    这可能是使用模板标签的好用例:

    @register.filter
    def get_item_from_dict(d, key):
        return d.get(key)
    

    在模板中,

    你可以这样做:

       {% for dict1_k, dict1_v in dict1.items %} {{ dict1_v|get_item_from_dict:k }} {% endfor %}

    根据评论,只是

    <td>{{ dict1|get_item_from_dict:k }}</td>
    

    【讨论】:

    • 哎呀,dict1 实际上只是一个简单的字典(参见上面的编辑)。使用你的过滤器,我得到一个“'int'对象没有属性'get'”错误......
    • 好的。然后进行相应的修改
    • 实际上我最终以不同的方式创建了字典,但无论如何感谢
    猜你喜欢
    • 2018-09-22
    • 2011-09-19
    • 2021-10-17
    • 1970-01-01
    • 2012-10-03
    • 2014-02-08
    • 2014-03-18
    相关资源
    最近更新 更多