获取 django 模板中条件的最后一个 for 循环迭代



我希望在 if 语句中的第一次迭代中添加类rounded-t-lg shadow,在最后一次迭代中添加rounded-b-lg shadow。我有以下代码:

{% for note in notes %}
{% if note.is_sticky %}
<div class="flex items-center">
<div class="{% if forloop.first %} rounded-t-lg shadow {% elif forloop.last %} rounded-b-lg shadow {% endif %}">
<!-- code -->     
</div>     
</div>
</div>
{% endif %}
{% endfor %}

我遇到的问题是forloop.last通常适用于最后一次迭代,而不是条件中的最后一次迭代。因此,如果我有三个对象,其中两个是粘性的,最后一个不是,则该类将应用于非粘性对象,因为它是"行"中的最后一个。

如何将类应用于is_sticky条件内的最后一个迭代,而不考虑不满足条件的对象?

理想情况下,您应该在视图中过滤notes列表,以便它只包含is_sticky == True的那些。 根据您的查询集,您可能只需要添加:

.filter(is_sticky=True)

我还认为您可能需要小心notes中只有 1 个元素的情况。 我猜您希望它上下四舍五入,因此您需要 2 个单独的if测试,而不是elsif.

{% for note in notes %}
<div class="flex items-center">
<div class="{% if forloop.first %} rounded-t-lg shadow{% endif %}{% if forloop.last %} rounded-b-lg shadow{% endif %}">
<!-- code -->          
</div>
</div>
{% endfor %}

这应该有效:

{% for note in notes %}
{% if forloop.first %}
{% if note.is_sticky %}
<div class="flex items-center">
<div class="rounded-t-lg shadow">
<!-- code -->     
</div>     
</div>
</div>
{% endif %}
{% elif forloop.last %}
{% if note.is_sticky %}
<div class="flex items-center">
<div class="rounded-b-lg shadow">
<!-- code -->     
</div>     
</div>
</div>
{% endif %}
{% endif %}
{% endfor %}

最新更新