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

Shopify开发:如何用Liquid获取商品颜色变体名称并添加到select下拉框

Shopify Liquid 实现商品颜色变体下拉选择框的方法

核心逻辑是先定位当前商品的颜色选项,收集对应的颜色值后渲染到select标签即可,以下是具体实现代码:

兼容全版本的实现方法

适用于所有Shopify版本,兼容性最好:

{% comment %} 匹配商品的颜色选项 {% endcomment %}
{% assign color_option_index = nil %}
{% for option in product.options %}
  {% if option.name == 'Color' or option.name == '颜色' %}
    {% assign color_option_index = forloop.index0 %}
    {% break %}
  {% endif %}
{% endfor %}

{% if color_option_index != nil %}
  {% comment %} 遍历所有变体收集颜色值并去重 {% endcomment %}
  {% assign color_names = '' | split: '' %}
  {% for variant in product.variants %}
    {% assign current_color = variant.options[color_option_index] %}
    {% unless color_names contains current_color %}
      {% assign color_names = color_names | push: current_color %}
    {% endunless %}
  {% endfor %}

  {% comment %} 渲染下拉选择框 {% endcomment %}
  <select name="color" id="product-color-select">
    {% for color in color_names %}
      <option value="{{ color | handleize }}">{{ color }}</option>
    {% endfor %}
  </select>
{% endif %}

简化实现方法

2021年之后上线的Shopify版本支持直接读取选项值列表,无需手动遍历去重,代码更精简:

{% assign color_option = product.options | where: "name", "Color" | first %}
{% if color_option %}
<select name="color" id="product-color-select">
  {% for color in color_option.values %}
    <option value="{{ color | handleize }}">{{ color }}</option>
  {% endfor %}
</select>
{% endif %}

自定义修改说明

  • 如果你后台设置的颜色选项名称不是Color或者颜色,把代码中对应判断的字符串替换为你自己的选项名即可
  • 若需要默认选中第一个颜色,在<option>标签内添加{% if forloop.first %}selected{% endif %}属性即可
  • handleize过滤器作用是将颜色名转换为符合URL规范的字符串,不需要可以直接删除,直接填写value="{{ color }}"即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 21:36:05