Use js variable with Shopify liquid tag

雨燕双飞 提交于 2021-02-11 14:56:25

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/58634635/use-js-variable-with-shopify-liquid-tag

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!