Title: Feature Request: Add optional Filter-Closure to 'first' Filter in Twig
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
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 ?
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".
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
I tried something in this PR, let's see what the Twig team think about it :)