skip to Main Content

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


  1. Chosen as 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>
    

  2. You may use this:

    {% javascript %}
        console.log({{product.metafields.custom.sample_name.value | json }});
    {% endjavascript %}
    

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search