繁体   English   中英

Django模板——迭代一个元组列表,每个元组都是一个字符串,字典

[英]Django template - iterate a list of tuples, each tuple is a string, dictionary

我有一本字典,它已经变成了一个排序列表,它创建了以下内容:

monthly_spend_provider = sorted(monthly_spend_provider.items(), key=lambda item: item[1]['cost'], reverse=True)
monthly_spend_provider
[
('PROVIDER A', {'cost': Decimal('10000'), 'symbol': '£'}), 
('PROVIDER B', {'cost': Decimal('9000'), 'symbol': '$'}), 
('PROVIDER C', {'cost': Decimal('8000'), 'symbol': '$'}), 
('PROVIDER D', {'cost': Decimal('7000'), 'symbol': '£'}), 
]

现在我试图访问 Django 模板中元组中的数据,但没有成功。

我认为下面会起作用,但它没有

{% for provider in monthly_provider_country %}
    {% for data in provider %}
    <h3>{{ provider }} {{ data.symbol }} {{ data.cost|currency }}</h3>
    {% endfor %}
{% endfor %}

我可以在模板中执行此操作还是有办法将排序列表转换回更简单的格式以输出到模板中?

编辑:原始字典

>>> monthly_spend_provider
{
    'PROVIDER B': {
        'cost': Decimal('9000'), 'symbol': '$'
        },
    'PROVIDER A': {
        'cost': Decimal('10000'), 'symbol': '£'
        },
    'PROVIDER D': {
        'cost': Decimal('8000'), 'symbol': '$'
        },
    'PROVIDER C': {
        'cost': Decimal('7000'), 'symbol': '£'
        }
}

谢谢

我相信你需要。

{% for provider, d in monthly_provider_country %}
    <h3>{{ provider }} {{ d.symbol }} {{ d.cost|currency }}</h3>
{% endfor %}

我认为你必须写你的<h3>标签如下...

<h3>{{ data.0 }} {{ data.1.symbol }} {{ data.1.cost|currency }}</h3>

试试这个:

{% for provider in monthly_provider_country %}
    {% for data in provider %}
    <h3>{{ data[0] }} {{ data[1].symbol }} {{ data[1].cost|currency }}</h3>
    {% endfor %}
{% endfor %}

暂无
暂无

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

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