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

Shopify如何实现产品含指定标签时渲染HTML且不重复展示

Shopify 产品NEW标识重复渲染修复方案

问题原因

原有代码会遍历所有产品标签,每匹配到一个包含new字符的标签就渲染一次NEW标识,因此当产品存在多个含new的标签时,会出现重复渲染的问题。

修复方案

方案1:循环匹配后直接终止(兼容原有模糊匹配逻辑)

在匹配到第一个符合条件的标签后,用{% break %}直接终止循环,仅渲染1次标识:

{% for tag in product.tags %}
  {% if tag contains 'new' %}
    <div class="new-tag new-tag--absolute"> NEW </div>
    {% break %}
  {% endif %}
{% endfor %}

方案2:判断与渲染分离(可维护性更高)

先标记是否存在符合条件的标签,再统一渲染标识,后续调整逻辑更方便:

{% assign has_new_tag = false %}
{% for tag in product.tags %}
  {% if tag contains 'new' %}
    {% assign has_new_tag = true %}
    {% break %}
  {% endif %}
{% endfor %}

{% if has_new_tag %}
  <div class="new-tag new-tag--absolute"> NEW </div>
{% endif %}

补充:仅匹配标签完全等于new的场景

如果你的需求是标签精确等于new才显示标识,不需要模糊匹配,可以直接用更简洁的数组判断,无需循环:

{% if product.tags contains 'new' %}
  <div class="new-tag new-tag--absolute"> NEW </div>
{% endif %}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 13:09:02