Django 模板 - for 循环然后 if 语句

Django template - for loop and then if statement

我有这个循环:

<div class="product-gallery-preview order-sm-2">
                            {% for images in Artikel.productimages_set.all %}
                            {% if images.Position == 1 %}
                                <div class="product-gallery-preview-item active" id="gallery{{ images.Position }}">
                            {% else %}
                                <div class="product-gallery-preview-item" id="gallery{{ images.Position }}">

问题是我认为所有 div 类 都处于活动状态,因为找到的第一张图片确实如此。 是否可以循环检查所有图片是否在位置 1 并只输出我尝试打印的 div 框?

您可以使用 forloop.counter...

{% if forloop.counter == 1 %}
  <div class="product-gallery-preview-item active" id="gallery{{ images.Position }}">
{% else %}
  ....
{% endif %}