
2025年2月12日より、Liquid テンプレートで配列を処理する方法を改善するために、次の新しいフィルターを導入しました。これで、冗長なループや複雑な条件付きロジックを記述しなくても、配列内の項目をすばやく取得または確認できるようになりました。
find フィルター
特定のプロパティ値を持つ配列の最初の項目を返します。 これには、プロパティ名と関連する値の両方を指定する必要があります。
構文
array | find: string, string
例
{% assign sample_collection_products = collections['sample'].products %}
{% assign test_product = sample_collection_products | find: "vendor", "test" %}
{{ test_product.price }}
findを使うことで直接そのオブジェクトが取得できます。
これまではwhereとfirstを使って最初の配列要素を取得していましたが、findを使うことでより簡潔に記述できます。
{% assign sample_collection_products = collections['sample'].products %}
{% assign test_product = test_product | where: "vendor", "test" | first %}
{{ test_product.price }}
find_index フィルター
特定のプロパティ値を持つ配列の最初の項目のインデックスを返します。 これには、プロパティ名と関連する値の両方を指定する必要があります。
構文
array | find_index: string, string
例
{% assign sample_collection_products = collections['sample'].products %}
{% assign test_product_index = sample_collection_products | find_index: "vendor", "test" %}
{{ test_product_index }}
CSSのクラス名につけてバッジの色分け表示などに使えそうですね。
has フィルター
配列内の項目が指定されたプロパティ値を持つかどうかを確認します。 これには、プロパティ名と関連する値の両方を指定する必要があります。
構文
array | some: string, string
例
{% assign sample_collection_products = collections['sample'].products %}
{% assign has_test_product = sample_collection_products | some: "vendor", "test" %}
{% if has_test_product %}
<p>test vendor found</p>
{% endif %}
今まではwhereとsizeを使って配列サイズが1以上あるかで確認していましたが、hasを使うことでより簡潔に記述できます。
{% assign sample_collection_products = collections['sample'].products %}
{% assign test_products = sample_collection_products | where: "vendor", "test" | size %}
{% if test_products %}
<p>test vendor found</p>
{% endif %}
reject フィルター
特定のプロパティ値を持つ配列の項目を除外します。 これには、プロパティ名と関連する値の両方を指定する必要があります。
構文
array | reject: string, string
例
{% assign sample_collection_products = collections['sample'].products %}
{% assign non_test_products = sample_collection_products | reject: "vendor", "test" %}
{% for product in non_test_products %}
<p>{{ product.title }}</p>
{% endfor %}
rejectがなかった場合は、whereとunlessを使って記述していました。なかなか直感的に記述できなかったので、rejectが追加されて嬉しいです。
{% assign sample_collection_products = collections['sample'].products %}
{% assign test_products = sample_collection_products | where: "vendor", "test" %}
{% for product in sample_collection_products %}
{% unless test_products contains product %}
<p>{{ product.title }}</p>
{% endunless %}
{% endfor %}
まとめ
これらの新しいフィルターを使用すると、配列内の項目をすばやく取得または確認できるようになります。これにより、冗長なループや複雑な条件付きロジックを記述する必要がなくなり、テンプレートの可読性が向上します。
ぜひこの機会に新しいフィルターを使ってリファクタリングしてみてください。