英文:
Shopify: how to access a Shopify metafield using JavaScript in a .liquid file?
问题
我正尝试在 .liquid 文件中使用 JavaScript 访问 Shopify 的元字段。该元字段是一个单行文本字段。
{% javascript %}
console.log({{product.metafields.custom.sample_name.value}});
{% endjavascript %}
一些我尝试过的建议,但未成功...
建议 1:在元字段周围加上引号
{% javascript %}
console.log('{{product.metafields.custom.sample_name.value}}');
{% endjavascript %}
建议 2:将元字段赋值给一个变量... 但似乎与直接使用元字段一样
{% assign tempVar = product.metafields.custom.sample_name.value %}
{% javascript %}
console.log(tempVar);
{% endjavascript %}
英文:
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 %}
答案1
得分: 0
以下是要翻译的内容:
您可以使用此代码:
<script>
console.log({{product.metafields.custom.sample_name.value | json }});
</script>
有关Liquid中json过滤器的更多信息:
https://shopify.dev/docs/api/liquid/filters/json
英文:
You may use this:
<script>
console.log({{product.metafields.custom.sample_name.value | json }});
</script>
More info about the json filter in liquid:
https://shopify.dev/docs/api/liquid/filters/json
答案2
得分: 0
原始问题是无法在Liquid JavaScript标签内呈现Liquid(?),即:
{% javascript %}{% endjavascript %}
但我发现在Liquid JS标签之外的脚本标签中仍然可以呈现Liquid...
所以像这样的内容可以正常工作...
英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论