I am trying to show what variants are available for each product on a store. While I have the code to do this working, each available variant should be comma separated except for the last one.
I have tried the append string filter, but that includes the last item.
I have tried using {% if forloop.last %} but the code will include the variant even if it is not available.
Here is my code:
{% if product.variants.size > 0 and product.available %}
{% unless product.has_only_default_variant %}
<span class="sizes-available">
Sizes in stock:
{% for variant in product.variants %}
{% if variant.available %}
{{ variant.title | append: ', '}}
{% endif %}
{% endfor %}
</span>
{% endunless %}
{% endif %}
If the product has three variants (size A, size B, size C) and size C is out of stock, my desired output is: size A, size B
Thanks in advance for your help with this.
2
Answers
Found the answer ... needs to be an array to use the join array filter.
Updated code:
You’re skipping an unknown number of elements, which could include the first or last element in the list – so we can’t rely on
forloop.first
orforloop.last
, as either one of these might be a skipped element.An alternate way to approach this situation where you need a comma after every element except the last one is to structure the code like this:
(Note: In the above example, I included the whitespace-stripping
-
‘s in the Liquid tags to remove all the excess line breaks/tabs/spaces between the tags. See https://shopify.github.io/liquid/basics/whitespace/ for more details)