【问题标题】:How to select the first item from a list [duplicate]如何从列表中选择第一项[重复]
【发布时间】:2014-11-26 11:31:20
【问题描述】:

我有以下 for 循环吐出列表中的所有照片:

{% 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 %}

如何只选择并显示列表中的第一张照片?

【问题讨论】:

    标签: python django jinja2


    【解决方案1】:

    {{ photos.0 }} 将是第一项。所以:

    {% 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 %}
    

    如果您仍想在模板中使用photo 变量(因为它比每次都索引更方便),请考虑使用{% with photo=photos.0 %} {# ... #} {% endwith %}

    【讨论】:

      【解决方案2】:

      您可以使用.0 访问第一个元素:

      将它与with标签结合(以最小化更改):

      {% 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 %}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多