Shopify product.liquid页jQuery问题:无法在变体单选按钮显示重量及单位
问题原因
- 你直接在JS的拼接逻辑里写Liquid过滤器
variant.weight | weight_with_unit: variant.weight_unit不会生效,因为Liquid是服务端渲染的代码,只会在页面首次加载时解析一次,JS运行时的变量不会再被Liquid处理。 - 你直接取
variant.weight_unit返回undefined,是因为Shopify默认的{{ product | json }}输出的变体对象中不包含weight_unit字段,仅返回以克为单位的weight数值。
解决步骤
步骤1:自定义产品JSON输出,补充重量相关字段
替换原来的var product = {{product | json}};代码,手动构造product对象,把需要的重量字段加进去:
var product = { id: {{ product.id | json }}, title: {{ product.title | json }}, options: {{ product.options | json }}, variants: [ {% for variant in product.variants %} { id: {{ variant.id | json }}, title: {{ variant.title | json }}, options: {{ variant.options | json }}, available: {{ variant.available | json }}, featured_image: {{ variant.featured_image | json }}, weight: {{ variant.weight | json }}, weight_unit: {{ variant.weight_unit | json }}, // 直接在服务端格式化好重量+单位,不用JS额外处理 formatted_weight: {{ variant.weight | weight_with_unit: variant.weight_unit | json }} }{% unless forloop.last %},{% endunless %} {% endfor %} ] };
步骤2:替换单选按钮的重量显示代码
找到你原来的拼接行,直接用已经格式化好的formatted_weight字段即可:
+ '<span class="variant-button-top"></span>' + variant.formatted_weight + '<span class="variant-button-bottom"></span>' +
补充说明
如果需要自定义单位换算规则,也可以直接用variant.weight(单位为克)和variant.weight_unit在JS中自行计算转换,无需依赖Liquid过滤器。修改后原有变体选择功能不受影响,仅额外新增了重量相关字段。
内容的提问来源于stack exchange,提问作者LuisV
相关产品推荐
相关产品推荐

