javascriptshopifyliquidmetaobject

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


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 %}

Solution

  • 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>