问题
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