Render something every nth iteration inside a collection page in liquid

Viewed 84

How can I add different list items that show e.g. an image after the third, seventh and eleventh list item which derive from the collection.products? I have tried jQuery but it did not work. Any idea?

<ul id="collection-grid" data-id="{{ section.id }}" class="grid">
  {%- for product in collection.products -%}
    <li class="grid-item">
      {% render 'product-wrapper' %}
     </li>
  {%- endfor -%}
 </ul>

<script>
   $( "ul:nth-child(3)" ).append( "<li class="info-card card-wrapper"><img...></li>" );
</script>

1 Answers

I don't know what HTML you'd like to add and where but I made a guess below.

Use the cycle tag and capture it in a variable and then use if to display what you'd like.

(No need for jQuery)

<ul id="collection-grid" data-id="{{ section.id }}" class="grid">
    {%- for product in collection.products -%}
        {% capture thisIteration %}{% cycle '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12' %}{% endcapture %}

        <li class="grid-item">
            {% render 'product-wrapper' %}
            {% if thisIteration == '3' %}
                <span>Here is the HTML that is added only on every 3rd iteration</span>
            {% endif %}
            {% if thisIteration == '7' %}
                <span>Here is the HTML that is added only on every 7th iteration</span>
            {% endif %}
            {% if thisIteration == '11' %}
                <span>Here is the HTML that is added only on every 11th iteration</span>
            {% endif %}
        </li>
    {%- endfor -%}
</ul>

There is also a modulo filter that you could use but with iterations like 7th and 11th I feel the above is more readable.

<ul id="collection-grid" data-id="{{ section.id }}" class="grid">
    {%- for product in collection.products -%}
        {% assign mod3 = forloop.index | modulo: 3 %}
        {% assign mod7 = forloop.index | modulo: 7 %}
        {% assign mod11 = forloop.index | modulo: 11 %}

        <li class="grid-item">
            {% render 'product-wrapper' %}
            {% if mod3 == 0 %}
                <span>Here is the HTML that is added only on every 3rd iteration</span>
            {% endif %}
            {% if mod7 == 0 %}
                <span>Here is the HTML that is added only on every 7th iteration</span>
            {% endif %}
            {% if mod11 == 0 %}
                <span>Here is the HTML that is added only on every 11th iteration</span>
            {% endif %}
        </li>
    {%- endfor -%}
</ul>
Related