Reputation: 23
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 %}
Upvotes: 0
Views: 2634
Reputation: 2173
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
Upvotes: 0
Reputation: 23
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>
Upvotes: 1