【问题标题】:How to show the first true element after if condition in for loop in django template?如何在django模板的for循环中显示if条件后的第一个真实元素?
【发布时间】:2021-10-18 12:05:13
【问题描述】:

我在 Django 模板中有一个 for 循环。之后,我检查巧合。但在某些情况下,可能有 3 个巧合。我只需要展示第一个巧合。现在,我的代码返回了 3 次名称,因为有 3 次巧合

{% for ip in ips %}
   {% if d.name == ip.name %}
        <strong>{{ d.name}} </strong>                               
   {% endif %}
{% endfor %}

解决方案 django模板中的forloop是无法破解的,所以决定在views.py中通过queryset区分相似名称进行更改

ips = Point.objects.defer('point').order_by('name').distinct('name')

【问题讨论】:

  • 请分享您的模型,这属于模板,因为它是业务逻辑。

标签: django for-loop django-templates


【解决方案1】:

我不建议在 Django Template 中这样做,而是在视图本身中这样做。但如果你不能,那么你可以使用{{ forloop|break }}

类似这样的:

{% for ip in ips %}
   {% if d.name == ip.name %}
        {{ forloop|break }}
        <strong>{{ d.name}} </strong>                               
   {% endif %}
{% endfor %}

查看小sn-p示例here...

【讨论】:

  • 谢谢,我决定在views.py中通过queryset区分相似名称来改变
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-11
  • 1970-01-01
  • 2012-09-09
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 2021-06-30
相关资源
最近更新 更多