How to print div each five iterations in a forloop

Hi guys, need to print products within a div each five products, so I can have 5 products inside a wrap.

this what I’m trying so far:

{% assign count = 0 %}
                 
{%- for product in collection.products -%}

{% if count == 5 %}
<div class="row">
{% endif %}
   {%- render 'product-card', product: product, stacked: true, show_badges: true -%}
                   
{% if count == 5 %}
</div>
{% endif %}

{% assign count = count | plus: 1 %}       

{% endfor %}

Hello @alealdev

Your code is almost there. You just need to add a closing tag for the div element after the last product card. Here is the complete code:

{% assign count = 0 %}

{% for product in collection.products %}

{% if count == 5 %}
<div class="row">
{% endif %}

  {% render 'product-card', product: product, stacked: true, show_badges: true %}

{% if count == 5 %}
</div>
{% endif %}

{% assign count = count | plus: 1 %}

{% endfor %}

This code will create a new div element with the class row after every 5 product cards. This will help you to display your products in a more organized way.

Please use this code. I have made some required changes in your code.

{% assign count = 0 %}

{% for product in collection.products %}
{%- render 'product-card', product: product, stacked: true, show_badges: true -%}

{% assign count = count | plus: 1 %}

{% if count == 5 %}

   

   
   {% assign count = 0 %}
   {% endif %}
{% endfor %}

  • Added an opening <div class="row"> before the loop starts.
  • Incremented the count variable by 1 for each iteration.
  • Added a conditional statement to check if count is equal to 5. If true, it closes the current row div and opens a new row div. It also resets the count variable to 0.
  • Added a closing </div> outside the loop to ensure that the last row is properly closed.