【问题标题】:Django template get element in list of dictionary by indexDjango模板按索引获取字典列表中的元素
【发布时间】:2018-08-06 03:08:18
【问题描述】:

我有以下几点:

item0 = [{'itemCode': 'AZ001', 'price': 15.52}, {'itemCode': 'AB01', 'price': 31.2}, {'itemCode': 'AP01', 'price': 1.2}]
item1 = [{'itemCode': 'BZ001', 'price': 12.55}, {'itemCode': 'BB01', 'price': 34.1}]

在 django 模板中,我想按索引显示每个列表元素的价格:15.52、12.55 然后 31.2、34.1 然后 1.2

列表大小可能不相等,所以我发送最大列表的大小。

迭代最大列表大小:

{{i.item|index:forloop.counter0}} 得到我{'itemCode': 'AZ001', 'price': 15.52}

如果我想要价格,我该怎么办?

执行{{i.item|index:forloop.counter0.price}} 会在索引 0 处给我无效的关键价格。

换句话说,我按列顺序发送元素,并希望在不使用服务器上的 zip 进行列表理解的情况下按行顺序显示它们。

有什么办法吗?

【问题讨论】:

  • 您可能需要提供更多上下文。通常不是使用模板标签来获取基于 forloop.counter0 的索引,而是直接遍历 item:{% for elem in i.item %}... {{ elem.price }}。为什么你不能这样做?
  • 我有多个列表,我正在相互比较。所以当我基于列发送它们时,我需要基于行显示它们。我可以在服务器上进行 zip,但在进行 zip 之前我正在尝试其他方式。
  • 此外,如果您尝试访问列表的第一个元素,那么您可以这样做:item.0.price
  • 你可以写一个custom template tag。然而,使用zip(或zip_longest 用于不同长度的列表)对我来说似乎是一种更好的方法。

标签: python django django-templates


【解决方案1】:

不确定我的问题是否正确,但这就是您要的代码。

views.py:

def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['item'] = [{'itemCode': 'AZ001', 'price': 15.52}, {'itemCode': 'AB01', 'price': 31.2}]
        return context

template.html:

{{ item.0.price }}

15.52 的结果


如果你想循环它,你可以这样做:

{% for i in item %}
    {{ i.price }}
{% endfor %}

在您更新问题后,我会执行以下操作:

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    item0 = [{'itemCode': 'AZ001', 'price': 15.52}, {'itemCode': 'AB01', 'price': 31.2}, {'itemCode': 'AP01', 'price': 1.2}]
    item1 = [{'itemCode': 'BZ001', 'price': 12.55}, {'itemCode': 'BB01', 'price': 34.1}]
    import itertools
    context['zip_longest'] = itertools.zip_longest(item0, item1)
    return context

template.html:

{% for element in zip_longest %}
    {% for item in element %}
        {% if item %}
            {{ item.price }} <br>
        {% endif %}
    {% endfor %}
{% endfor %}

结果:

15.52 
12.55 
31.2 
34.1 
1.2 

在我看来,使用 zip_longest 并没有错,因为它会从生成器中生成值。

【讨论】:

  • 编辑问题以解释更多
【解决方案2】:
<ul>
     {% for key, value in dictionary.items %}
     <li><a href="{{key}}">{{value}}</a></li>
     {% endfor %}
</ul>

试试这个,reference

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 2015-05-25
    • 2013-12-03
    • 2018-11-15
    • 1970-01-01
    • 2011-06-06
    • 2014-05-12
    相关资源
    最近更新 更多