0
votes

I am trying to create a global boolean variable and use it to check if a condition is met. If the condition is met perform a certain action and set to true so that the next time the action is not performed.

Here is the code I was trying to use, currently it looks like the global variable is not a affected and its always set to true and the action always takes place.

Thank you in advance! And any recommendations on how to dry this will be appreciated.

{% assign firstFound = false %}

{% if product.metafields.pdm.product-details %}
    {% if firstFound == false %} {% assign firstFound = true %} {% endif %}
    <li><button type="button" class="reset {% if firstFound == true %}active{% endif %}" data-target="details">Product Details</button></li>
{% endif %}

{% if settings.about_diamonds %}
    {% if firstFound == false %} {% assign firstFound = true %} {% endif %}
    <li><button type="button" class="reset {% if firstFound == true %}active{% endif %}" data-target="diamonds">About Our Diamonds</button></li>
{% endif %}

{% if settings.shipping_returns %}
    {% if firstFound == false %} {% assign firstFound = true %} {% endif %}
    <li><button type="button" class="reset {% if firstFound == true %}active{% endif %}" data-target="shipping">Shipping and Returns</button></li>
{% endif %}
1
If the variable is never defined then it will never give you true / false. check for variable is exist or not below might help github.com/Shopify/liquid/issues/89Bhargav Kaklotara
@BhargavKaklotara my mistake I missed a line when I copied it over, I am defining the variable before everything else. I updated the code example.Alex Kinejara

1 Answers

0
votes

I believe that your code is working as it should. You're setting the firstFound variable to true so the active class is assigned to all your buttons. If you want to assign the class only to the first displayed button, you need to change your code to something like that:

{% assign firstFound = false %}

{% if product.metafields.pdm.product-details %}
    <li><button type="button" class="reset{% unless firstFound %}{% assign firstFound = true %} active{% endunless %}" data-target="details">Product Details</button></li>
{% endif %}

{% if settings.about_diamonds %}
    <li><button type="button" class="reset{% unless firstFound %}{% assign firstFound = true %} active{% endunless %}" data-target="diamonds">About Our Diamonds</button></li>
{% endif %}

{% if settings.shipping_returns %}
    <li><button type="button" class="reset{% unless firstFound %}{% assign firstFound = true %} active{% endunless %}" data-target="shipping">Shipping and Returns</button></li>
{% endif %}