Why does this not work in Django?
{% for img in image_list %}
{% if img != image_list[-1] %}
<img src="{% get_media_prefix %}{{ img.image }}" alt="Recipe Image Secondary">
<br>
{% endif %}
{% endfor %}
Simple Python (works):
for img in image_list:
if img != (image_list[-1]):
print(img)
{% if img != image_list[-1] %}
throws a TemplateSyntaxError Could not parse the remainder: '[-1]' from 'image_list[-1]'
CodePudding user response:
You can work with the |last
template filter [Django-doc] to obtain the last item of a sequence:
{% for img in image_list %} {% if img != image_list|last %} <img src="{{ img.image.url }}" alt="Recipe Image Secondary"> <br> {% endif %} {% endfor %}
or in this case work with forloop.last
[Django-doc]:
{% for img in image_list %} {% if not forloop.last %} <img src="{{ img.image.url }}" alt="Recipe Image Secondary"> <br> {% endif %} {% endfor %}
CodePudding user response:
{% for img in image_list %}
{% if not forloop.last %}
<img src="{% get_media_prefix %}{{ img.image }}" alt="Recipe Image Secondary">
<br><br>
{% else %}
<img src="{% get_media_prefix %}{{ img.image }}" alt="Recipe Image Secondary">
{% endif %}
{% endfor %}