如何在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
相关产品推荐
相关产品推荐

