PHPackages                             balint777/twig-lambda - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Search &amp; Filtering](/categories/search)
4. /
5. balint777/twig-lambda

ActiveLibrary[Search &amp; Filtering](/categories/search)

balint777/twig-lambda
=====================

Lambda expressions for Twig and filters that make use of them

v2.0.0(5y ago)053MITPHPPHP ^5.6 || ^7.0

Since May 2Pushed 5y agoCompare

[ Source](https://github.com/balint777/twig-lambda)[ Packagist](https://packagist.org/packages/balint777/twig-lambda)[ RSS](/packages/balint777-twig-lambda/feed)WikiDiscussions master Synced 1w ago

READMEChangelogDependencies (3)Versions (10)Used By (0)

Twig Lambda
===========

[](#twig-lambda)

> Lambda expressions for Twig and filters that make use of them

---

Quick examples
--------------

[](#quick-examples)

Listing names of all authors ordered by age:

```
{% for author in articles|map(=> _.author)|unique_by('===')|sort_by(=> _.age) %}
    * {{ author.name }}, {{ author.age }}
{% endfor %}
```

Counting elements starting from specified letter:

```
{% for key, count in ['foo', 'bar', 'foobar']|countBy(=> _|first|capitalize) %}
    * {{ count }} elements start from {{ key }}.
{% endfor %}
```

---

Installation
------------

[](#installation)

**Install via Composer:**

```
composer require dpolac/twig-lambda
```

**Add the extension to Twig:**

```
$twig->addExtension(new \DPolac\TwigLambda\LambdaExtension());
```

**... or if you use Symfony**, add the following to your `services.yml` config file:

```
services:
    # ...
    dpolac.twig_lambda.extension:
        class: DPolac\TwigLambda\LambdaExtension
        tags: [ { name: twig.extension } ]
```

---

Usage
-----

[](#usage)

### Lambda expression

[](#lambda-expression)

To create lambda expression prepend any valid Twig expression with `=>` operator. Inside of the lambda expression you can use any variable from the outside. There are also two special variables available:

- `_` (single underscore) - first argument,
- `__` (double underscore) - array of arguments counted from zero.

```
=> _.name
=> _ * 2
=> _|first
=> 'foobar'
=> _ is even
=> __[0] + __[1]

```

To create lambda expression with list of arguments, add it before `=>` operator. Separate multiple arguments with semicolons. You can use brackets for readability.

```
x => x + 1
(book) => book.author
arg1; arg2 => arg1 ~ arg2
(a; b; c) => a + b - c

```

Note that if you use list of arguments, `_` variable is not longer available.

---

Below is a list of available filters and tests. All works with arrays and any Traversable object and preserve it keys. All lambdas are called with two arguments: element and key.

---

### |map

[](#map)

**Alias:** `|select`
**Signature:** `array|map(lambda)`

Applies a given function to each element and returns array of results in the same order.

```
{% for i in  [1, 2, 3, 4]|map(=> _ * 2) %}
    {{ i }} {# prints '2 4 6 8' #}
{% endfor %}
```

---

### |filter

[](#filter)

**Alias:** `|where`
**Signature:** `array|filter(lambda)`

Returns array of elements that passes a test specified by lambda.

```
{% for i in [1, 2, 3, 4, 5, 6]|filter(=> _ is even) %}
    {{ i }} {# prints '2 4 6' #}
{% endfor %}
```

---

### |unique\_by

[](#unique_by)

**Signature:** `array|unique_by(lambda|'==='|'==')`

Returns array of unique elements. Uniqueness is checked with passed lambda. PHP operators == or === will be used if string '==' or '===' is passed instead of lambda.

Lambda should have two arguments - items to check. Keys of elements are also passed as third and fourth argument.

```
    {% for i in [1, 2, 2, 3, 1]|unique_by((i1;i2) => i1 == i2) %}
        {{ i }} {# prints '1 2 3' #}
    {% endfor %}
```

equivalent

```
    {% for i in [1, 2, 2, 3, 1]|unique_by('==') %}
        {{ i }} {# prints '1 2 3' #}
    {% endfor %}
```

---

### |group\_by

[](#group_by)

**Signature:** `array|group_by(lambda)`

Sorts an array into groups by the result of lambda.

```
{% for key, group in ['foo', 'bar', 'foobar', 'barbar']|group_by(=> _|first|capitalize) %}
    = {{ key }}
    {% for i in group %}
        * {{ i }}
    {% endfor %}
{% endfor %}
```

will produce

```
    = F
        * foo
        * foobar
    = B
        * bar
        * barbar

```

---

### |sort\_by

[](#sort_by)

**Signature:** `array|sort_by(lambda[, direction = 'ASC'])`

Sorts array by values returned by lambda. Direction can be 'ASC' or 'DESC'.

```
{% for i in ['bar', 'fo', 'foobar', 'foob']|sort_by(=> _|length, 'DESC') %}
    {{ i }} {# prints 'foobar foob bar fo' #}
{% endfor %}
```

---

### |count\_by

[](#count_by)

**Signature:** `array|count_by(lambda)`

Sorts an array into groups and returns a count for the number of objects in each group.

If lambda returns true, false or null, it will be converted to string 'true', 'false' or 'null'. Float will be converted to integer.

```
{% for key, count in ['foo', 'bar', 'foobar']|count_by(=> _|first|capitalize) %}
    * {{ count }} elements start from {{ key }}.
{% endfor %}
```

will produce

```
    * 2 elements start from F
    * 1 elements start from B

```

---

### is any

[](#is-any)

**Signature:** `array is any(lambda)`

Returns true if lambda returns true for any element from an array.

**Returns false if array is empty.**

```
{{ [1, 2, 3] is any(=> _ is even) ? "There is even element in the array." }}
{# prints 'There is even element in the array.' #}
```

---

### is every

[](#is-every)

**Signature:** `array is every(lambda)`

Returns true if lambda returns true for every element from an array.

**Returns true if array is empty.**

```
{{ [1, 2, 3] is every(=> _ > 0) ? "All elements in the array are positive." }}
{# prints 'All elements in the array are positive.' #}
```

---

### call()

[](#call)

**Signature:** `call(lambda [, arguments:array])`

Calls lambda and returns its result. You can provide array of arguments.

This function is provided to allow creating twig macros taking lambda as an argument.

```
{{ call(=> _ * 2, [10]) }}
{# prints '20' #}
{{ call(=> _.foo, [{foo: 12}]) }}
{# prints '12' #}
```

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 77.1% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~223 days

Recently: every ~389 days

Total

8

Last Release

2103d ago

Major Versions

v0.5.0 → v1.0.02018-06-06

v1.0.0 → v2.0.02020-08-14

PHP version history (2 changes)v0.1.0PHP ^5.4 || ^7.0

v1.0.0PHP ^5.6 || ^7.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/4ffdbd430f6f574c049ec2a8c4f0522af7d7926c5886d5f174b4002235f104ad?d=identicon)[balint777](/maintainers/balint777)

---

Top Contributors

[![dpolac](https://avatars.githubusercontent.com/u/18581845?v=4)](https://github.com/dpolac "dpolac (27 commits)")[![crabnky](https://avatars.githubusercontent.com/u/2010148?v=4)](https://github.com/crabnky "crabnky (4 commits)")[![moknomo](https://avatars.githubusercontent.com/u/2641095?v=4)](https://github.com/moknomo "moknomo (3 commits)")[![balint777](https://avatars.githubusercontent.com/u/4312347?v=4)](https://github.com/balint777 "balint777 (1 commits)")

---

Tags

filtermapsortfunctionfunctionaluniquelambdagroup

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/balint777-twig-lambda/health.svg)

```
[![Health](https://phpackages.com/badges/balint777-twig-lambda/health.svg)](https://phpackages.com/packages/balint777-twig-lambda)
```

###  Alternatives

[dpolac/twig-lambda

Lambda expressions for Twig and filters that make use of them

45205.4k1](/packages/dpolac-twig-lambda)[kitpages/data-grid-bundle

Symfony DataGridBundle

7780.9k1](/packages/kitpages-data-grid-bundle)[chemem/bingo-functional

A simple functional programming library.

716.9k3](/packages/chemem-bingo-functional)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
