Search code examples
shopifyliquid

Resetting loop count on liquid on condition


I'm trying to eliminate discontinued products from the recommended products section on Shopify. Using Liquid, I'm checking if the product contains the tag 'discontinued' and skipping it.

The issue I'm facing is that the for loop has a limit of 4, so when it encounters a product with the tag, it skips, but when it reaches 4, it stops, resulting in an incomplete array of products on the front end.

So, I need to find a way to increment the loop count by 1 when it finds a discontinued product.

{%- for product in related_collection.products limit: number_of_products -%}
            {% comment %} On smaller screen sizes, 39vw is used for grid items in the CSS {% endcomment %}
            {% if product.tags contains 'discontinued' %}
              {% increment number_of_products %}
            {% else %}
                {%- render 'product-grid-item',
                    product: product,
                    per_row: section.settings.products_per_row,
                    quick_shop_enable: settings.quick_shop_enable,
                    fallback: '39vw',
                -%}
            {% endif %}
          {%- endfor -%}

The code above is what i'm using to filter the prodcuts but the increment loop count is not working.


Solution

  • Managed to find a solution:

    {%- if related_collection.products_count > 0 -%}
          <div class="product-recommendations page-width">
            <div class="product-grid grid--uniform" data-aos="overflow__animation">
              {%- for product in related_collection.products -%}
                {% comment %} On smaller screen sizes, 39vw is used for grid items in the CSS {% endcomment %}
                {% unless product.tags contains 'discontinued' %}
                    {%- render 'product-grid-item',
                        product: product,
                        per_row: section.settings.products_per_row,
                        quick_shop_enable: settings.quick_shop_enable,
                        fallback: '39vw',
                    -%}
                    {%- assign rendered_products = rendered_products | plus: 1 -%}
                {% endunless %}
                {% if rendered_products == number_of_products %}
                  {% break %}
                {% endif %}
              {%- endfor -%}
            </div>
          </div>
        {%- endif -%}