How to use better loop for my product images I have a main product image and 4 thumbnails. Main product image is a lightswitch which is named productMainImage.

Here below i first iterate for the main image (which lightswitch is on) and than i make a second for loop for 4 thumbnails.

My problem is i don't like this code and it seems inefficient. I have to go out and go in for the loop because of my html stucture.

Can anyone help me to write this better?

&lt;!-- Product Image --&gt;
&lt;div class="small-12 medium-5 column"&gt;
  &lt;div class="row"&gt;
    {% for image in product.productImages %}
      {% if image.productMainImage %}
        &lt;div class="small-12 column"&gt;
          &lt;a class="fancybox" rel="gallery1" href="{{image.getUrl()}}"&gt;&lt;img src="{{image.getUrl('productPageMainImage')}}" alt=""&gt;&lt;/a&gt;
        &lt;/div&gt;
        {% endif %}
    {% endfor %}
    &lt;div class="small-12 column"&gt;
      &lt;div class="row small-collapse medium-uncollapse"&gt;
        {% for image in product.productImages %}
        &lt;div class="small-3 column"&gt;
          &lt;a class="fancybox" rel="gallery1" href="{{image.getUrl()}}"&gt;&lt;img src="{{image.getUrl('productPageThumbnail')}}" alt=""&gt;&lt;/a&gt;
        &lt;/div&gt;
        {% endfor %}
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;&lt;!-- Product Image END --&gt;
One way to do this is to query for the images once, and sort them into two different arrays. This uses twig's merge filter, which is the way to add things to an array in twig.

{% set mainImages = [] %}
{% set otherImages = [] %}

{% for image in product.productImages %}
  {% if image.productMainImage %}
    {% set mainImages = mainImages | merge([image]) %}
  {% else %}
    {% set otherImages = otherImages | merge([image]) %}
  {% endif %}
{% endfor %}


Then you can loop over the mainImages array to get the images with the lightswitch on, and the otherImages array to get the other images.

You will have three for loops, but only one database query.