JMKelley
JMKelley

Reputation: 658

Shopify check if Metafield exists?

I'm looking to hide content if the metafields are empty for a product, but right now it's returning it for all pages which means my if statement is broken somewhere.

Product Page

{% if product.metafields.review %}
  {% include 'extra-review' %}
{% else %}
{% endif %}

Review Snippet Page (extra-review.liquid)

{% assign review = product.metafields.review %}
{% assign key = 'author' %}
{% assign key = 'author-img' %}
{% assign key = 'long' %}

<p> Hello world </p>

Any help would be brilliant

EDIT

Added review metafields layout

enter image description here

Upvotes: 8

Views: 20135

Answers (2)

Jason
Jason

Reputation: 896

To check if a namespace exists you can do a comparison against blank. For example:

{% if product.metafields.review != blank %}
  ...
{% endif %}

You could also used the size if you wanted to ensure you had three keys. Here we simply output the size:

{{ product.metafields.review.size }}

More info on truthy/falsy can be found in the Shopify docs: https://help.shopify.com/themes/liquid/basics/true-and-false

Upvotes: 20

bknights
bknights

Reputation: 15377

Truthiness in Liquid is not like Javascript. I've been bitten by this a few times:

Your test should be:

{% if product.metafields.review == true %}
...
{% endif %}

and review in product.metafields.review is the namespace of the review metafields. see https://help.shopify.com/themes/liquid/objects/metafield

Upvotes: 3

Related Questions