【问题标题】:Looping only through first image in Liquid仅循环通过 Liquid 中的第一个图像
【发布时间】:2021-02-17 13:10:27
【问题描述】:

我在 Shopify 中使用下一个代码来显示与变体图像中的“alt”文本匹配的图像。 尽管我只通过 CSS 显示第一张图片,但这个 markdown 会循环遍历所有图片并大大降低页面速度;导致很多图片被隐藏。

有没有办法只循环第一张图片?

{% for image in product.images %}
 {% if image.alt == variant.title %}
  <img class="hidde" data-src="{{ image | img_url: '800x' }}" src="{{ image | img_url: '800x' }}" alt="{{ image.alt | escape }}" />
 {% endif %}
{% endfor %}

提前致谢,

【问题讨论】:

    标签: loops for-loop shopify liquid


    【解决方案1】:

    如果您有多个具有相同变体标题的图片 alt,您可以在匹配后中断循环。

    {% for image in product.images %}
     {% if image.alt == variant.title %}
      <img class="hidde" data-src="{{ image | img_url: '800x' }}" src="{{ image | img_url: '800x' }}" alt="{{ image.alt | escape }}" />
      {% break %}
     {% endif %}
    {% endfor %}
    

    {% break %} 将在 if 语句变为 true 时停止循环。

    但所有这些都可以通过 where 过滤器完成,如下所示:

    {% assign title = variant.title %}
    {% assign images = product.images | where: "alt", title %}
    {% if images.size > 0 %}
      <img src="{{ images[0] | img_url: '800x' }}" alt="{{title | escape }}">
    {% endif %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-04
      • 2014-08-28
      • 2020-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      相关资源
      最近更新 更多