skip to Main Content

On my website, I show some products with a condition – if the product has a test tag:

{% if product.tags contains 'test' %}
   // render product
{% endif %}

And this way I get only some products, but the native product filter still displays the count of all products. I’ll check it this way:

{% for filter in collection.filters %}
  {% for value in filter.values %}
    {{ value.count }}, 
  {% endfor %}
{% endfor %}

And like I said, I get the full amount of products. But I want to get only the number of products that I displayed by condition. Can you please tell me how to do this? Thank you!

2

Answers


  1. In the for-loop that you use to render products you can create a count variable and use it later.

    pseudocode:

    {% liquid
      assign counter = 0
      for product in products
         assign counter = counter | plus: 1
         render 'product-div'
      endfor
      render 'counter', count: counter
    %}
    

    this solution isn’t elegant but the easiest one. If you need a counter in ‘product-div’ you can create two exact same for-loops: one for counting and second one for rendering.

    Again, this solution is not the most clever one but the beauty lies in simplicity and simple code is always the best one

    Login or Signup to reply.
  2. I think what you need to do is the following:

    1. Loop through all products in your collection
    2. Filter through them using your tag
    3. Assign an index to each of those products
    4. Then print the last recorded index
    5. List item

    In liquid this look pretty much like this:

    {% for filter in collection.filters %}
     {% if product.tags contains 'test' %}
      {% if forloop.last %}
        {{forloop.index0}}
      {% endif%}
     {%endif %}
    {% endfor%}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search