For Loop question (need modulo) This post is outdated
Someone in Support just asked:
Is there access to a modulus function in forloop constructs. I need to render X products in batches of four, and luckily for me, I need to detect every 4th iteration... and I don't see that in the provided Liquid. Is there a math filter I do not know about? I saw ones like plus, and minus... {{ some.size | plus: 1}} for example... I really do not want to use funky javascript for this... I do not think paginate helps here either.
There's no modulo function in Liquid that I know of, but that's where the cycle tag comes in handy: http://wiki.shopify.com/UsingLiquid#Cycle
<ul>
{% for product in collection.products %}
<li class="item-{% cycle '1', '2', '3', '4' %}">{{ product.title }}</li>
{% endfor %}
</ul>
Usually helps a lot. By the sound of what you're saying, this may not help. In that case, you can use some math.
<ul>
{% for product in collection.products %}
<li>{{ forloop.index }} :
{% capture modulo %}{{ forloop.index | divided_by: 4 }}{% endcapture %}
{% unless modulo contains '.' %}We are hitting a multiple of 4 my friends.{% endunless %}
</li>
{% endfor %}
</ul>
Posts:
Cool. Thanks for that tip.
Posts:
Very good tip Caroline!
Posts:
That solution didn't quite work for me when I tested it using Vision. However, it did give me enough info to come up with this...
{% for variant in product.variants %} {% capture thecycle %}{% cycle '1', '2', '3' %}{% endcapture %} {% if thecycle == '1' %}<div>{% endif %} <span>"{{ variant.title }}"><br></span> {% if thecycle == '3' or forloop.last %}</div>{% endif %} {% endfor %}That let me put div tags around every 3 variants
Posts:
Math filters don't work in Vision.
Posts:
To add a class to every 3rd element of a list:
<ul> {% for product in collection.products %} <li class="{% cycle '', '', 'last' %}"> .... </li> {% endfor %} </ul>Every 4th:
<ul> {% for product in collection.products %} <li class="{% cycle '', '', '', 'last' %}"> .... </li> {% endfor %} </ul>Etc.
Posts:
True, some nonsense went on back then.. in the day.. of course.. a little snippet that cleanly wraps three "block" things within a "slide" thing. Imagine the possibilities...
{% for product in collections.featured-crap.products %} {% cycle '<div class="slide">','','' %} <div class="block">Product {{forloop.index}}</div> {% cycle '','','</div>' %} {% endfor %}