首页 > 解决方案 > Liquid - 了解“where”的使用

问题描述

我正在尝试在 shopify 中创建一个导航菜单,如果客户有标签“X”并且该标签一个集合,则在菜单中显示相应的集合链接。虽然我不确定我是否正确理解了“where”属性的使用。

我完全是新鲜的液体,所以请原谅任何错误。

根据文档,位于此处。'Where',创建一个数组,只包含具有给定属性值的对象,或者默认情况下任何真值。所以理论上我认为我可以在我的链接数组中使用它。

这是文档的示例

All products:
{% for product in products %}
  {{ product.title }}
{% endfor %}

{% assign kitchen_products = products | where: "type", "kitchen" %}

Kitchen products:
{% for product in kitchen_products %}
  {{ product.title }}
{% endfor %}


Output:
All products:
 - Vacuum
 - Spatula
 - Television
 - Garlic press
    
Kitchen products:
 - Spatula
 - Garlic press

这是我的尝试

<!-- custom collection loop for sidebar navigation -->
{% if customer.tags != blank %}
  {% assign link = linklists.main-collections.links | where: link.title, customer.tags %} // This line in particular...
    {% for link in linklists.main-collections.links %}
        {% assign outer_index = forloop.index %}
        {% if link.links != blank %}
            {% assign has_active_link = false %}
            {% if link.active or link.child_active %}
                {% assign has_active_link = true %}
            {% endif %}
            <li class="site-nav--has-submenu site-nav__item"></li>
        {% else %}
            <li class="site-nav__item {{ collection.handle }}-collection {% if link.active %} site-nav--active{% endif %}">
                <a href="{{ link.url }}" class="site-nav__link" {% if link.active %} aria-current="page" {% endif %}>{{ link.title | escape }}</a>
            </li>
        {% endif %}
    {% endfor %}
{% endif %}
<!-- / end custom collection loop for sidebar navigation -->

对我的问题的任何指导将不胜感激。

进一步澄清:

客户 A 有标签 Apple、Pear、Peach

存在 Apple、Pear Peach 的系列

预期输出:

<ul>
  <li><a href="/apple">Apple</a></li>
  <li><a href="/pear">Pear</a></li>
  <li><a href="/peach">Peach</a></li>
</ul>

标签: shopifyliquid

解决方案


由于两个原因,它不会那样工作。

  1. 第一部分where采用对象的字段属性键link。所以而不是link.title,它应该是"title"
  2. 第二部分应该是完全匹配的条件,例如“Apple”或“Pear”。customer.tags是一个数组,或者 Shopify 将其称为“drop”。

在这里,由于标签总是唯一的,我们不需要使用where

您需要循环标记以及链接。试试这个循环

{% if customer.tags.size >0  %}
{% for tag in customer.tags %}
{% for link in linklists.main-collections.links %}
{% if link.title == tag %}

... do magic here ...

{% endif %}
{% endfor %}
{% endfor %}
{% endif %}

推荐阅读