Shopify变体图片色板适配问题:重复显示同一变体图片
问题:Shopify主题色板重复显示同一张变体图片
我正在适配一个原本使用颜色色板的Shopify主题,要改成用变体图片作为色板,但目前所有色板都重复显示同一张变体图片,无法对应每种可用颜色显示各自的变体图。
现有代码
{%- liquid assign color_file_name = value | handle | append: '.' | append: swatch_file_extension assign color_image = color_file_name | file_img_url: '50x50' | prepend: 'https:' | split: '?' | first assign color_swatch_fallback = value | split: ' ' | last | handle -%} <label for="{{ section.id }}-{{ option.name }}-{{ forloop.index0 }}" class="color__swatch color__swatch--{{ block.settings.swatch_type }}" style="--swatch-background-image: url({% for variant in product.variants %}{{ variant.image | img_url: 'small' }}{% endfor %}); height:50px; width:50px;" title="{{ value | escape }}" ><span class="color__swatch-dot"></span> </label>
问题表现
所有颜色色板均显示同一张产品图片,未匹配对应颜色的变体图。
修复方案
问题出在原有代码遍历了所有产品变体并输出图片URL,最终只会生效最后一个变体的图片。需要修改为筛选当前颜色对应的变体,再获取其图片:
修改后的代码
{%- liquid assign color_file_name = value | handle | append: '.' | append: swatch_file_extension assign color_image = color_file_name | file_img_url: '50x50' | prepend: 'https:' | split: '?' | first assign color_swatch_fallback = value | split: ' ' | last | handle // 筛选当前颜色对应的变体 assign matching_variants = product.variants | where: option.name, value assign matching_variant = matching_variants | first -%} <label for="{{ section.id }}-{{ option.name }}-{{ forloop.index0 }}" class="color__swatch color__swatch--{{ block.settings.swatch_type }}" // 用对应变体的图片,无图片时回退到原色板图片 style="--swatch-background-image: url({{ matching_variant.image | img_url: 'small' | default: color_image }}); height:50px; width:50px;" title="{{ value | escape }}" ><span class="color__swatch-dot"></span> </label>
修改说明
- 新增
matching_variants和matching_variant变量,通过where过滤器筛选出与当前颜色选项匹配的变体 - 将背景图片的URL替换为匹配变体的图片,同时保留原
color_image作为无图片时的回退方案
内容的提问来源于stack exchange,提问作者New Forest
相关产品推荐
相关产品推荐

