使用Liquid找出最后匹配的元素

时间:2017-04-12 20:12:41

标签: for-loop if-statement shopify liquid case-statement

我正在为Shopify商店开发自定义解决方案,我的问题是我无法管理如何避免在case语句中的最后一个匹配标记之后添加'/'。

我尝试将一些if语句与forloop过滤器结合使用,但没有结果 我想到的最后一件事就是在循环中找到最后一个匹配的标记,这将有助于我们在最后一个元素之后避免'/',但不幸的是我无法管理如何做到这一点。

预期结果:羊毛/尼龙/粘胶纤维

以下是将分配给产品的所有标签与输出所需的标签列表(服装材料)进行比较的代码部分。
考虑到产品具有羊毛,尼龙和粘胶等标签,非材料。

示例1

实际&预期结果: WoolNylonViscose

{% for tag in product.tags %}
{% case tag %}
    {% when 'Viscose' %}
    Viscose
    {% when 'Wool' %}
    Wool
    {% when 'Polyamide' %}
    Polyamide
    {% when 'Nylon' %}
    Nylon
    {% else %}
{% endcase %}
{% endfor %}

示例2

过滤器forloop.last用于定义循环的最后一个元素,但问题是材料标签(羊毛,尼龙,粘胶)可以位于产品标签数组的中间。考虑到产品有10个标签,材料标签分布在阵列中,我们将看到下一个结果。

结果: ///羊毛/尼龙////粘胶//

{% for tag in product.tags %}
    {% if forloop.last == true %}
        {% case tag %}
                {% when 'Viscose' %}
                Viscose
                {% when 'Wool' %}
                Wool
                {% when 'Nylon' %}
                Nylon
                {% else %}
        {% endcase %}
    {% else %}
        {% case tag %}
                {% when 'Viscose' %}
                Viscose
                {% when 'Wool' %}
                Wool
                {% when 'Nylon' %}
                Nylon
                {% else %}
        {% endcase %}
        /
    {% endif %}
{% endfor %}

如果您能指出我的错误并建议我如何实现解决方案,我将不胜感激。

2 个答案:

答案 0 :(得分:0)

您可以尝试以下方法: -

{% for tag in product.tags %}
{% case tag %}
    {% when 'Viscose' %}
     {{ 'Viscose' | append: '/' }}
    {% when 'Wool' %}
     {{ 'Wool' | append: '/' }}
    {% when 'Polyamide' %}
     {{ 'Polyamide' | append: '/' }}
    {% when 'Nylon' %}
     {{ 'Nylon' }}
    {% else %}
{% endcase %}
{% endfor %}

答案 1 :(得分:0)

这应该有效:

{% capture tag_string %}{% endcapture %}
{% for tag in product.tags %}
  {% if tag == 'Viscose' %}{% capture tag_string %}{{ tag_string }}Viscose/{% endcapture %}
  {% elsif tag == 'Wool' %}{% capture tag_string %}{{ tag_string }}Wool/{% endcapture %}
  {% elsif tag == 'Polyamide' %}{% capture tag_string %}{{ tag_string }}Polyamide/{% endcapture %}
  {% elsif tag == 'Nylon' %}{% capture tag_string %}{{ tag_string }}Nylon/{% endcapture %}
  {% endif %}
{% endfor %}
{{ tag_string | split: "" | reverse | join: "" | remove_first: "/" | split: "" | reverse }}

有关字符串过滤器的更多信息:https://help.shopify.com/themes/liquid/filters/string-filters