skip to Main Content

I am looping through products and I need the cycle tag based on loop.

{% for product in collection.products %}
   {% render 'product-grid-item', product: product %}
{% endfor %}

Inside the "product-grid-item", I have:

{% assign class_1 = 'small-6 medium-4' %}
{% assign class_2 = 'small-6 medium-3' %}
{% capture grid_item_width %}
   {% cycle class_1, class_1, class_1, class_2, class_2, class_2, class_2 %}
{% endcapture %}

The cycle is not working, because it is not directly inside the "for loop". Any idea how to get this working?

I am aware of alternatives, I am just trying to make "cycle" work inside a render tag.

2

Answers


  1. Render is a closed piece of code, it can’t read what is happening outside of it.

    So at the moment you not only don’t have access to the cycle but you don’t have access to the forloop object as well.

    You are looking for how the include works but that is deprecated and you shouldn’t use it.

    So the short answer is you can’t make it work, since the main logic of the render is to work this way.

    The only way to make the render aware of something outside it is to pass a variable to it, so you need to make your cycle logic outside of it and pass the resulting variable inside of it.

    Login or Signup to reply.
  2. What you are trying to do is possible as long as you rearrange your approach slightly. You will just need to do your math outside of the snippet and pass an appropriate value as a variable into the snippet.

    {% assign class_array = 'class-1,class-1,class-1,class-2,class-2,class-2,class-2' | split: ',' %}
    {% for product in collection.products %}
      {% assign loop_position = forloop.index0 | modulo: class_array.size %}
      {% render 'product-grid-item', product: product, class_name: class_array[loop_position] %}
    {% endfor %}
    

    How this works

    Just like before, we make a comma-separated array of class names that we want to cycle through. (We cannot make an array directly, but we can turn a delimited string into an array pretty easily using the split filter) – but this time we assign that to a variable.

    We then use the forloop index and the modulo operator to get a value between 0 and the last index position of our array list and use that number as the lookup value for our array. That value is passed into the rendered snippet so that product-grid-item can access it.

    If we ever need to change our cycling class names, all we have to do is update the array with the new values. Even if the number of values changes in the future, the code will still work to cycle through all of the values provided.

    Cheers!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search