Shopify Liquid中如何将循环获取的article.tags数组转小写实现标签匹配?
解决方案
问题原因
- Liquid的
downcase过滤器仅支持对字符串生效,article.tags是数组类型,直接应用过滤器不会生效 - 你之前在
for循环外调用article.tags时,循环还未执行,article变量尚未定义,自然无法拿到对应文章的标签数据
修复方案(二选一即可)
方案1:标签数组转小写字符串匹配(写法简洁)
通过join过滤器先把标签数组转为字符串再做大小写转换,为了避免部分匹配(比如匹配bag时误命中bagpack),可以给字符串和目标标签前后都加上分隔符做精准匹配:
{% assign taggs = "T-shirt,bag,Purse,Handbag" | split: "," %} {%- assign length = b_s.related_article_blog_count | plus: 0 -%} {% capture fourthtag %}{{ taggs[3] | downcase }}{% endcapture %} <!-- 给目标标签前后加逗号,用于精准匹配 --> {% assign target_tag = "," | append: fourthtag | append: "," %} <div class="jj-post-content"> <div class="item"> {%- for article in blogs[blog].articles limit: length -%} <!-- 把当前文章的标签转成逗号分隔的全小写字符串,前后加逗号 --> {% assign article_tags_str = article.tags | join: "," | downcase | prepend: "," | append: "," %} {% if article_tags_str contains target_tag %} <a href="{{ article.url }}"> <div class="jj-title">{{ article.title }}</div> </a> {%- endif -%} {%- endfor -%} </div> </div>
方案2:遍历单标签逐个匹配(匹配精度最高)
遍历当前文章的每一个标签,单独转小写后和目标标签匹配,完全避免部分匹配问题:
{% assign taggs = "T-shirt,bag,Purse,Handbag" | split: "," %} {%- assign length = b_s.related_article_blog_count | plus: 0 -%} {% capture fourthtag %}{{ taggs[3] | downcase }}{% endcapture %} <div class="jj-post-content"> <div class="item"> {%- for article in blogs[blog].articles limit: length -%} {% assign tag_matched = false %} <!-- 遍历当前文章的所有标签 --> {% for tag in article.tags %} {% if tag | downcase == fourthtag %} {% assign tag_matched = true %} {% break %} {% endif %} {% endfor %} {% if tag_matched %} <a href="{{ article.url }}"> <div class="jj-title">{{ article.title }}</div> </a> {%- endif -%} {%- endfor -%} </div> </div>
内容的提问来源于stack exchange,提问作者Jetro Olowole
相关产品推荐
相关产品推荐

