How to select the first item from a list [duplicate]

耗尽温柔 提交于 2019-12-25 07:08:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!