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