You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopify 如何正确在每个商品variant上显示对应重量

问题原因
  • 作用域引用错误:在{% for value in option.values %}循环内直接调用{{ variant.weight | weight_with_unit }}时,variant指向的是页面初始加载的默认变体,不是当前循环选项对应的变体,会导致所有选项都显示同一个重量,和预期不符。
  • 语法笔误:代码首行的{{ variant. weight }}在对象名和属性名之间多了空格,会导致Liquid渲染报错。
  • 属性冗余:选项容器的data-property属性中混入了无关的重量字段,会干扰前端选项切换的正常逻辑。
修复方案

核心逻辑是渲染每个选项值时,先匹配该值对应的变体,再读取对应变体的重量字段渲染,同时修正语法错误。
修正后的完整代码如下:

<div class="product-options__section d-flex flex-wrap" data-style="text" data-property="{% render 'product-get-options-strip-symbols' with value: option.name %}"{% if disable_auto_select %} data-disable-auto-select{% endif %}>
    {%- for value in option.values -%}
        {% include 'product-get-options-res-status' with option_index0: option_index0 %}
        {% comment %} 查找当前选项值匹配的变体 {% endcomment %}
        {% assign target_variant = null %}
        {% for variant in product.variants %}
            {% if variant.options[option_index0] == value %}
                {% assign target_variant = variant %}
                {% break %}
            {% endif %}
        {% endfor %}
        <div class="product-options__value product-options__value--text d-flex flex-center border cursor-pointer{% if disabled_value %} disabled{% elsif hidden_value %} disabled-hidden{% endif %}{% if active_value %} active{% endif %}"
             data-js-option-value
             data-value="{% render 'product-get-options-strip-symbols' with value: value %}"
             {{ trigger_attr }}
             data-scale="2"
        >
            {{ value | replace: '<', '&lt;' | replace: '>', '&gt;' }}
            {% if target_variant %}
                <span class="variant-weight">({{ target_variant.weight | weight_with_unit }})</span>
            {% endif %}
            <span></span>
        </div>
    {%- endfor -%}
</div>
补充说明
  • 重量外层的括号和variant-weight类名是为了方便调整样式,你可以根据自身设计需求修改分隔符、样式类。
  • 如果商品有多个选项维度(比如同时有颜色、规格两个选项),上述代码会匹配当前维度下选项值对应的变体重量;如果需要实现用户切换不同选项组合时重量实时更新,只需要在原有变体切换的JS回调中,拿到当前选中的变体对象,更新对应重量标签的文本内容即可。

内容的提问来源于stack exchange,提问作者Carlvic Lim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 00:27:22