You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
feature #2996 Add "filter", "map", and "reduce" filters (fabpot)
This PR was squashed before being merged into the 1.x branch (closes#2996).
Discussion
----------
Add "filter", "map", and "reduce" filters
This PR adds support for 3 new filters: `filter`, `map`, and `reduce`. They take an arrow function as an argument (a PHP closure).
I have restricted the usage of arrow functions as much as possible as it makes no sense to support them everywhere. So, for now, they are only accepted as arguments to filters (using them as arguments to function is not supported but could be easily added if we have a use case).
The syntax is the following: `(x) => x + 3` where `(x)` is the list of arguments, `=>` starts the body, and the body is any Twig expression. Within the arrow function, the context is also available: `(x) => x + offset` works if `offset` is defined in the current context.
~~These new filters will allow us to deprecate the `if` support on the `for` tag, which does not work well with the `loop` variable:~~
```twig
{% set sizes = {xs: 34, s: 36, m: 38, l: 40, xl: 42} %}
{# before #}
{% for name, size in sizes if size < 38 %}
{{ name }} = {{ size }}
{% loop.last ? 'LAST' %} {# <--- works with this PR #}
{% endfor %}
{# after #}
{% for name, size in sizes|filter(size => size < 38) %}
{{ name }} = {{ size }}
{{ loop.last ? 'LAST' }}
{% endfor %}
```
This closes#2785
Commits
-------
5c15f89 added the key to the map and filter filters
13274bb added support for iterators
175041e removed fn in front of arrow functions
dc27763 changed arrow syntax
b30bce1 added "filter", "map", and "reduce" filters
@@ -558,7 +621,7 @@ public function parseArguments($namedArguments = false, $definition = false)
558
621
thrownewSyntaxError(sprintf('A default value for an argument must be a constant (a boolean, a string, a number, or an array).'), $token->getLine(), $stream->getSourceContext());
0 commit comments