Ad

Use Js Variable With Shopify Liquid Tag

- 1 answer

Currently in Shopify we can create a file.js.liquid which grants access to liquid functionality.

<script>
var liquidData = {
  myValue: {{ product.image | asset_url }}
}
</script>

How can I use a variable in the placeme of product.image? In example:

var myVar = 'something.jpg'
    var liquidData = {
      myValue: {{ myVar | asset_url }}
    }

Currently this does not work for me the path it out puts is myVar as a string not as a variable. I also tried concatenation and it also reads the variable name as a string. Any ideas?

Ad

Answer

You must remember that liquid is executed before the DOM. This applies to Javascript files as well.

The liquid code is executed before the JS file is processed so when you create a JS variable and try to pass it to liquid is not possible since liquid finished it's execution long before the Javascript started to execute.

So to sum it up you can't pass anything from the Javascript ot Liquid, but the other way is possible.


So back to your question.

It should look like so:

{% assign myVar = 'something.jpg' %}
var liquidData = {
  myValue: "{{ myVar | asset_url }}"
}
Ad
source: stackoverflow.com
Ad