如何在django模板中使用if-else语句中断循环



我阅读了Django文档中的if-else语句但我不明白我的情况。我有照片列表,如果是COVER,我想要渲染图像,否则我想要渲染静态图像。这是我的代码

{% for x in listing.photos.all %}
{% if x.photo_tipo == 'COVER' %}
<img src="{{ x.get_thumb }}" alt="">
{% else %}
<img src="{% static 'images/about/1.jpg' %}" alt="">
{% endif %}
{% endfor %}

结果是:如果x.photo=='COVER',则为一个图像,列表中每隔一张照片为一个静态图像。如果声明为真,我只想得到一个结果,如果声明为假,我只希望得到一个静态图像

不要在模板中执行此操作。在某个地方添加一些逻辑,如果存在,可以直接为您提供该类型的照片。一个好的方法是在Listing模型上使用一个方法:

class Listing(models.Model):
...
def cover_photo(self):
return self.photos.filter(photo_tipo='COVER').first()

现在你的模板可以是:

{% with photo as listing.cover_photo %}
{% if photo %}
<img src="{{ photo.get_thumb }}" alt="">
{% else %}
<img src="{% static 'images/about/1.jpg' %}" alt="">
{% endif %}
{% endwith %}

最新更新