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

如何在Liquid模板文件中提取去重后的唯一值

问题原因

  • capture 块内输出 {{color}} 时,各值之间的分隔符是换行和空白字符,不是你预设的逗号+空格,后续 split: ", " 操作无法将不同颜色拆分为独立数组元素,所有内容会被识别为单个数组元素,uniq 去重自然无效。
  • 即使修正分隔符,捕获内容首尾多余的空白也会导致去重失效,需要额外处理空白字符。

修复代码

推荐直接在循环内构建数组,无需通过capture中转,逻辑更简洁:

{% assign color_array = "" | split: "" %}
{% for tag in product.tags %}              
  {% if tag contains 'pair' %} 
    {% assign tag_split = tag | remove_first: 'pair::' | split: "::" %}
    {% assign color = tag_split[0] | strip %}
    {% assign color_array = color_array | push: color %}
  {% endif %}
{% endfor %}
              
<p>{{ color_array | uniq | join: ", " }}</p>

保留原capture写法的修正版本:

{% capture items %}
  {% for tag in product.tags %}              
    {% if tag contains 'pair'%} 
      {% assign tag_split = tag | remove_first: 'pair::' | split: "::" %}
      {% assign color = tag_split[0] | strip %}
      {{ color }},
    {% endif %}
  {% endfor %}              
{% endcapture %}

{% assign my_array = items | strip | remove_last: "," | split: "," | uniq %}
<p>{{ my_array | join: ", " }}</p>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 19:27:02