How do I make a control flow tag for metadata objects?

I am editing the card-product.liquid file in the Dawn theme with the intent of showing a metafield string with the product title.

Here is my metadata object:

{{ card_product.metafields.shopify["dietary-preferences"] | metafield_text: field: 'label' | escape }}

I would like to make a control flow tag so that the HTML with the string is only generated if the field has a string. The key in the Settings → Custom Data → Metaobjects is shopify--dietary-preferences.label

When I tried to make the flow control tag, I did not know how to write the variable properly. So I tried the following, but it did not work:

{% if card_product.metafields.shopify--dietary-preferences.label != null %}
<p class="product__text inline-richtext caption-with-letter-spacing">{{ card_product.metafields.shopify["dietary-preferences"] | metafield_text: field: 'label' | escape }}</p> 
{% endif %}

Any ideas?

Hey @moraitis!

You’re super close with your code. The issue is just a small syntax detail when accessing the field:

{% if card_product.metafields.shopify--dietary-preferences.value.label != null %}
<p class="product__text inline-richtext caption-with-letter-spacing">{{ card_product.metafields.shopify["dietary-preferences"] | metafield_text: field: 'label' | escape }}</p> 
{% endif %}

The key part you were missing is .value. before the label field.

Thank you so much for the help! I really appreciate your prompt reply. I found a great help page that echoes your helpful advice about .value:

Here is what I ended up doing:

{% assign content_check = item.product.metafields.shopify["dietary-preferences"] | metafield_text: field: 'label' %}
{% if content_check != null %}
<!-- insert dietary preferences -->
<p class="caption-with-letter-spacing">{{ item.product.metafields.shopify["dietary-preferences"] | metafield_text: field: 'label' | escape }}</p>
{% endif %}

This example is from line 104 of main-cart-items.liquid.

Despite trying every combination of the dot syntax I could think of, I only had empty values that never worked with my control flow statement if ... != null. The only reason I had the item.product.metafields.shopify["dietary-preferences"] | metafield_text: field: 'label' text was because it was automatically generated when I used the visual editor to insert a metafield.

Thanks again!