How To Select The First Item From A List
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 %}
Solution 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 %}
Solution 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 %}
Post a Comment for "How To Select The First Item From A List"