Fabien Potencier 3d95ffe906 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
-------

5c15f897 added the key to the map and filter filters
13274bbf added support for iterators
175041e0 removed fn in front of arrow functions
dc277635 changed arrow syntax
b30bce11 added "filter", "map", and "reduce" filters
2019-05-09 13:18:48 +02:00
2019-05-03 10:32:27 +02:00
2019-03-20 19:20:25 +01:00
2019-02-15 06:17:13 +01:00
2019-05-01 10:06:25 +02:00
2019-05-03 10:32:27 +02:00
2019-05-01 10:58:08 +02:00
2019-01-01 18:34:43 +01:00
2018-04-20 07:23:43 +02:00

Twig, the flexible, fast, and secure template language for PHP
==============================================================

Twig is a template language for PHP, released under the new BSD license (code
and documentation).

Twig uses a syntax similar to the Django and Jinja template languages which
inspired the Twig runtime environment.

More Information
----------------

Read the `documentation`_ for more information.

.. _documentation: https://twig.symfony.com/documentation
Languages
PHP 99.9%