2

Realizing Twig can't escape a for loop, how would one go about setting a variable for the current item and not the following?

Scenario; Color swatches are radio buttons, if default purchasable stock <= 0 and default purchasable unlimitedStock == false, the next radio button should be checked, and if this has stock <= 0 and so on, you get the idea, the next would be checked.

I can't seem to find a way to only check the next, and not all the following radio buttons if previous purchasable in the loop is out of stock.

A lot of checking of the checkers being checked here. Hah.

1

Here's a simple solution that might be viable for your scenario:

{% set selected = false %}
{% for purchasable in product.variants %}
    {% if selected == false and (purchasable.stock > 0 or purchasable.unlimitedStock) %}
        {# output selected radio #}
        {% set selected = true %}
    {% else %}
        {# output unselected radio #}
    {% endif %}
{% endfor %}

Essentially set a variable (selected in this case) that once set cannot be re-set, and is only set under the circumstances you mentioned (stock available or unlimitedStock set to true).

  • That did the trick perfectly! Can't believe how simple that was, borderline ashamed I didn't think of it. – Anders Oct 11 '16 at 20:48
1

Check out the MN Twig Perversion plugin. It adds a break Twig tag, which allows you to escape from a loop once you have the data you need.

  • Trying to avoid adding too many plugins, but this seems useful nonetheless. Many thanks for the tip! – Anders Oct 9 '16 at 0:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.