Skip to content

Commit

Permalink
Adds where filter (#1415)
Browse files Browse the repository at this point in the history
  • Loading branch information
diana-lakatos committed Dec 4, 2023
1 parent 4e6cede commit 2a44760
Showing 1 changed file with 89 additions and 0 deletions.
89 changes: 89 additions & 0 deletions app/views/pages/api-reference/liquid/filters.liquid
Original file line number Diff line number Diff line change
Expand Up @@ -1714,3 +1714,92 @@ Converts any URL-unsafe characters in a string into percent-encoded characters.
```liquid
{{ "Thomas Edison" | url_encode }}
```

## where

Creates an array including only the objects with a given property value, or any `truthy` value by default.

In this example, assume that you have a list of products and you want to show your kitchen products separately. Using `where`, you can create an array containing only the products that have a `"type"` of `"kitchen"`.

#### Input

```liquid
{% raw %}
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 %}
{% endraw %}
```

#### Output

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

Kitchen products:
- Spatula
- Garlic press
```

Say instead you have a list of products and you only want to show those that are available to buy. You can use `where` with a property name but no target value to include all products with a truthy `"available"` value.

#### Input

```liquid
{% raw %}
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 %}
{% endraw %}
```

#### Output

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

Available products:
- Coffee mug
- Boring sneakers
```

The `where` filter can also be used to find a single object in an array when combined with the first filter. For example, say you want to show off the shirt in your new fall collection.

#### Input

```liquid
{% raw %}
{% assign new_shirt = products | where: "type", "shirt" | first %}
Featured product: {{ new_shirt.title }}
{% endraw %}
```

#### Output

```liquid
Featured product: Hawaiian print sweater vest
```

0 comments on commit 2a44760

Please sign in to comment.