Reputation: 151
I'm using the next code in Shopify in order to show the images matching the 'alt' text from the variant image. Despite I'm only showing the first image via CSS, this markdown loops through all the images and slows down the page a lot; resulting in lots of images hidden.
Is there a way to loop only through the first image?
{% 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 %}
Thanks in advance,
Upvotes: 0
Views: 3278
Reputation: 12943
If you have multiply images alt with the same variant title you can break of the loop once you have a match.
{% 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 %}
The {% break %}
will stop the loop once there the if statement becomes true.
But all of this can be done with a where
filter, like so:
{% 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 %}
Upvotes: 2