where

创建一个仅包含具有给定属性值的对象,或默认情况下包含任何真值的对象的数组。

在这个例子中,假设你有一个产品列表,你想分别展示你的厨房产品。使用 where,你可以创建一个仅包含 "type""kitchen" 的产品的数组。

输入

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 %}

输出

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

Kitchen products:
- Spatula
- Garlic press

假设你有一个产品列表,并且只想显示那些可以购买的产品。你可以使用 where 加上属性名称,但不使用目标值来包含所有 真值"available" 的产品。

输入

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

{% assign available_products = products | where: "available" %}

Available products:
{% for product in available_products %}
- {{ product.title }}
{% endfor %}

输出

All products:
- Coffee mug
- Limited edition sneakers
- Boring sneakers

Available products:
- Coffee mug
- Boring sneakers

当与 first 过滤器组合使用时,where 过滤器还可以用于在数组中查找单个对象。 例如,假设你想展示你的新秋季系列中的衬衫。

输入

{% assign new_shirt = products | where: "type", "shirt" | first %}

Featured product: {{ new_shirt.title }}

输出

Featured product: Hawaiian print sweater vest