New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Title: Feature Request: Add optional Filter-Closure to 'first' Filter in Twig #3962
Comments
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 |
Thank you, fixed that.
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 |
This filter returns the first _value_ matching the given arrow function or null Attempt to solve twigphp#3962 (open to any feedback)
I tried something in this PR, let's see what the Twig team think about it :) |
This filter returns the first _value_ matching the given arrow function or null Attempt to solve twigphp#3962 (open to any feedback)
This filter returns the first _value_ matching the given arrow function or null Attempt to solve twigphp#3962 (open to any feedback)
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 thefirst
filter by adding an optional parameter that allows users to specify a filter closure. This closure would enable thefirst
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:
In this example,
firstAboveTen
would be13
, as it's the first number in the list that is greater than10
.Another example:
Output:
2
The text was updated successfully, but these errors were encountered: