Henry31
Henry31

Reputation: 105

Shopify Liquid Theme advance custom field checkbox if-statement did not understand "true" as truthy

I have added a few checkboxes to my products in Shopify via the Advanced Custom Fields plugin.

In the theme I would like to iterate through these checkboxes and only if the checkbox has been checked do I want to display a specific translation text here.

However, I fail on the IF statement to check whether the checkbox is checked or not.

Here is my code (with some debugging output)

<ul>
  {% for field in product.metafields.warnhinweise %}
    {% assign field_first = field | first %}
    {% assign field_last = field | last %}
    <li>ID: {{ field_first }} - Value: {{ field_last }}</li>

    {% assign language_key = 'products.productwarnings.' | append: field_first %}

      {% if field_last == true %}
        <ul>
          <li>ID: {{ field_first }} - Value: {{ field_last }}</li>
          <ul>
            <li>nest the variable output: {{ language_key  | t }}</li>
          </ul>
        </ul>
      {% else %}
        <ul>
          <li>don't show</li>  
        </ul>
      {% endif %}
  {% endfor %}
</ul>

Here is the Output:

As you cann see, no output

Conclusion: Maybe true is not truthy?

I tried this as well, to check for a string:

{% if field_last == 'true' %}

But this leads to the same result.

And here is a screenshot from the Advanced Custom Fields backend

Advance Custom Fields Config 1

Here is the exemplary configuration of a checkbox.

Advance Custom Fields Config 2 - from a Checkbox Item

I really wonder why such a simple IF statement doesn't work here?

Thanks a lot in Advance for you help.

Upvotes: 1

Views: 4685

Answers (1)

Dave B
Dave B

Reputation: 3248

The metafields may not be being stored in a format that exactly matches your comparison

When Shopify prints values to your document, it can sometimes be hard to what the data type of the underlying value was. For example, if true is being printed to the document, is that because the value was the boolean true, the string "true", an array of values that contains ['true'], or something else?

To find out what the exact value being used under-the-hood is, I recommend using the | json filter to output your variable. By using something like {{ field_last | json }}, Shopify will convert the variable into a javascript-legal format and will include all special characters (and some special characters like quotation marks will be escaped by the \ character), thereby revealing what the underlying structure is.

In your case, it looks like the metafield value is array-like. Rather than going for an exact match on this construction, I would suggest switching the equality operator (==) in your comparison for the contains keyword:

{% if field_last contains 'true' %}
  <!-- Cool feature goes here! -->
{% endif %}

Upvotes: 1

Related Questions