Twig icon indicating copy to clipboard operation
Twig copied to clipboard

Title: Feature Request: Add optional Filter-Closure to 'first' Filter in Twig

Open rkrx opened this issue 1 year ago • 4 comments

Twig already offers a first filter that is used to retrieve the first value of a list (array, iterable). This feature request proposes an enhancement to the first filter by adding an optional parameter that allows users to specify a filter closure. This closure would enable the first filter to skip over entries that do not match the expression defined in that filter closure.

Use Case

This enhancement would be particularly useful in scenarios where users need to fetch the first item from a list that meets certain criteria, rather than just the first item in the list. For example, in a list of numbers, a user might want to retrieve the first number that is greater than 10, or in a list of strings, the first string that contains a certain substring.

Example

Here's an example of how this might look in practice:

{% set numbers = [1, 2, 13, 4, 5] %}
{% set firstAboveTen = numbers|first(value => value > 10) %}

In this example, firstAboveTen would be 13, as it's the first number in the list that is greater than 10.

Another example:

{% set attributes = [{name: 'a', value: 1}, {name: 'b', value: 2}, {name: 'c', value: 2}] %}
{{ attributes|first(a => a.name == 'b').value }}

Output: 2

rkrx avatar Jan 12 '24 14:01 rkrx

You probably meant "first" instead of "filter" in your last example ?

{{ attributes|first(a => a.name == 'b').value }}

But that is related to what i was going to say: is this really a gain compared to |filter(..)|first ?

smnandre avatar Jan 13 '24 21:01 smnandre

You probably meant "first" instead of "filter" in your last example ?

Thank you, fixed that.

But that is related to what i was going to say: is this really a gain compared to |filter(..)|first ?

Yes, but that's more verbose and a predicate for first is a pretty obvious read. This is how Kotlin defines a first-"filter".

rkrx avatar Jan 13 '24 22:01 rkrx

Yes, but that's more verbose and a predicate for first is a pretty obvious read. This is how Kotlin defines a first-"filter".

Similar to "Array.find" in JS too

smnandre avatar Jan 13 '24 23:01 smnandre

I tried something in this PR, let's see what the Twig team think about it :)

smnandre avatar Jan 13 '24 23:01 smnandre