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
Answers
The original issue is liquid cannot be rendered within liquid JavaScript tags (?) i.e.:
but I found liquid can still be rendered within script tags outside of liquid js tags...
So something like this will work...
You may use this:
More info about the json filter in liquid:
https://shopify.dev/docs/api/liquid/filters/json