How to print div each five iterations in a forloop

alealdev
Shopify Partner
5 0 0

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 %}
Replies 2 (2)

magecomp
Shopify Partner
264 20 32

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.
 
 
Helping voluntarily. Please like and accept the solution if it helps. Thanks!
Our Bestseller Shopify Apps    |      Mobile App Builder by MageComp    |      Limit Qty Purchase

Need a developer?  Just visit MageComp website

Akibhusen
Shopify Partner
715 121 148

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

 

{% assign count = 0 %}

<div class="row">
{% for product in collection.products %}
{%- render 'product-card', product: product, stacked: true, show_badges: true -%}

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

{% if count == 5 %}

   </div>
   <div class="row">
   {% assign count = 0 %}
   {% endif %}
{% endfor %}

</div>

 

 

  • 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.