How to use arrow functions as callable?
Closed this issue · 10 comments
I'd be really great if Twig arrow functions can be passed as arguments.
e.g. Laravel collections unique method accepts a callable.
I'd like to do something like this:
{{ mycollection.unique(item => item.id) }}
Is that possible? Or an RFC?
It's not supported. Arrow functions are limited in scope.
@fabpot okay... but why not keep this is an RFC?
It would be very useful to have more flexibility to filter/sort arrays or collection objects.
I'd love to see this as well! Specifically, would use here: https://github.com/timkelty/craftcms-classmate#arrow-functions
@fabpot Would you consider making $allowArrow
configurable, i.e. opt-in on a per-Environment basis?
The ability to pass tiny little closures to Collection methods would be really nice. I definitely appreciate the spirit of limiting arrow functions to narrow usage, but the Collections use case is very compelling.
To make this work this one line: https://github.com/twigphp/Twig/blob/3.x/src/ExpressionParser.php#L483 from:
foreach ($this->parseArguments() as $n) {
to:
foreach ($this->parseArguments(false, false, true) as $n) {
then closures all work in the context we want, e.g.:
{% set collection = collect(['a', 'b', 'c']) %}
{% set contains = collection.contains((value, key) => value == 'a') %}
with a nice, clean, normal syntax. I'd love to see this happen, too.
Would really love to see this as well. When writing templates, it’s really confusing why arrow functions work in some cases but not others, when you know the underlying method accepts a callable.
Here's a solution for Craft CMS: https://github.com/nystudio107/craft-closure
Would really love to see this as well.
Anyone who is interested in this, I added it here: #3951 (comment)