Shopify: how to access a Shopify metafield using JavaScript in a .liquid file?

1.1k Views Asked by At

I am trying to access a Shopify metafield using JavaScript in a .liquid file. The metafield is a single line text field.

{% javascript %}

  console.log({{product.metafields.custom.sample_name.value}});

{% endjavascript %}

Some things I've tried from suggestions elsewhere that did not work...

Suggestion 1: put quotes around the metafield

{% javascript %}

  console.log('{{product.metafields.custom.sample_name.value}}');

{% endjavascript %}

Suggestion 2: assign the metafield to a variable... but this seems to still be the same as just directly using the metafield

{% assign tempVar = product.metafields.custom.sample_name.value %}
{% javascript %}

  console.log(tempVar);

{% endjavascript %}
2

There are 2 best solutions below

0
On BEST ANSWER

The original issue is liquid cannot be rendered within liquid JavaScript tags (?) i.e.:

{% javascript %}{% endjavascript %}

but I found liquid can still be rendered within script tags outside of liquid js tags...

<script></script> 

So something like this will work...

<script>
console.log({{product.metafields.custom.sample_name.value }});
</script>
4
On

You may use this:

<script>
    console.log({{product.metafields.custom.sample_name.value | json }});
</script>

More info about the json filter in liquid: https://shopify.dev/docs/api/liquid/filters/json