问题
I have the following for
loop that spits out all photos in a list:
{% if photos %}
{% for photo in photos %}
{% thumbnail photo.photo "100x100" crop="center" as im %}
<img src="{{ im.url }}" alt="User's photos" data-ajax="{% url 'photo_increase_view' pk=photo.id %}"/>
{% endthumbnail %}
{% endfor %}
{% endif %}
How can I just select and display the first photo in the list?
回答1:
You can access the first element using .0
:
Combine it with with tag (to minimize changes):
{% if photos %}
{% with photo=photos.0 %}
{% thumbnail photo.photo "100x100" crop="center" as im %}
<img src="{{ im.url }}" alt="User's photos" data-ajax="{% url 'photo_increase_view' pk=photo.id %}"/>
{% endthumbnail %}
{% endwith %}
{% endif %}
回答2:
{{ photos.0 }}
will be the first item. So:
{% if photos %}
{% thumbnail photos.0.photo "100x100" crop="center" as im %}
<img src="{{ im.url }}" alt="User's photos" data-ajax="{% url 'photo_increase_view' pk=photos.0.id %}"/>
{% endthumbnail %}
{% endif %}
If you want to still use the photo
variable in the template (since its more convenient than indexing every time), consider using {% with photo=photos.0 %} {# ... #} {% endwith %}
来源:https://stackoverflow.com/questions/26144524/how-to-select-the-first-item-from-a-list