我希望在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条件下将类应用于最后一次迭代?
答案 0 :(得分:1)
理想情况下,您应该在视图中过滤Status
列表,因此它仅包含sudo apt-get install python-setuptools
所在的列表。根据您的查询集,您可能只需要添加:
notes
我还认为,is_sticky == True
中只有1个元素时,您可能需要谨慎对待。我想您希望将其四舍五入,因此您需要2个单独的.filter(is_sticky=True)
测试,而不是notes
。
if
答案 1 :(得分:0)
这应该有效:
{% 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 %}