Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Twig Lambda Laravel Package

dpolac/twig-lambda

Adds lambda and arrow-function syntax to Twig templates, letting you write inline closures like map((x) => x * 2) directly in your templates. A small, focused extension for cleaner data transformations without custom filters or PHP callbacks.

Deep Wiki
Context7

Getting Started

The package is a Twig extension that adds inline (params) => expression lambda syntax, plus functional filters (filter, map, reduce, sort, group_by) that consume those lambdas. It is not a Laravel package — Laravel ships Blade, not Twig, so you only adopt this if you are already running Twig via rcrowe/twigbridge or a hand-wired \Twig\Environment.

  1. Install it:

    composer require dpolac/twig-lambda
    
  2. Register the extension on the Twig environment:

    use Dpolac\TwigLambda\LambdaExtension;
    
    $twig->addExtension(new LambdaExtension());
    

    With twigbridge, add it to config/twigbridge.php under extensions (or register it from a service provider so it is present before any view is compiled).

  3. First use case — filtering an array inline instead of in the controller:

    {{ [1, 2, 3, 4, 5]|filter(n => n is even)|join(', ') }}
    

    Before this package you would either pre-filter in PHP or write an ugly {% for %}{% if %} loop. The lambda collapses that into a single expression.

Where to look first: the extension's LambdaExtension class to confirm which filters it registers on your installed version (the filter set has drifted across releases), and composer.lock / composer why-not to see which Twig version it settled on. The 2018 last-release date is the single most important thing to verify before you build on it.

Implementation Patterns

Array pipelines. Lambdas compose naturally with Twig's pipe operator; treat them like Laravel collections but in the template:

{% set active = users
     |filter(u => u.active and u.role != 'guest')
     |map(u => u.name)
     |sort %}

Custom comparators. sort accepts a two-argument lambda:

{{ products|sort((a, b) => a.price <=> b.price) }}

Prefer the spaceship over subtraction for non-numeric keys.

Reduce for aggregation. The carry is the first bound parameter:

{% set total = cart|reduce((sum, item) => sum + item.qty * item.price, 0) %}

Grouping. group_by returns a map keyed by the lambda's return value — handy for building tabbed or sectioned views without controller-side grouping:

{% for role, people in users|group_by(u => u.role) %}
  <h2>{{ role }}</h2>
  ...
{% endfor %}

Reusable lambdas. Depending on version, lambdas can be bound to a variable and invoked later:

{% set byName = (a, b) => a.name <=> b.name %}
{% set sorted = people|sort(byName) %}

Use this to avoid repeating the same arrow expression across a template.

Integration tips.

  • Keep the "which filters exist" contract explicit — different versions of the package expose slightly different helpers, so do not assume every functional filter is present.
  • Wrap collection-shaping logic (sorts, groupings used by more than one template) in a Twig function in a small custom extension rather than embedding fragile arrow chains in every view.
  • Test rendering through a real compiled template in a feature test, not just instantiating the extension — most failures here are parse-time, not runtime.

Gotchas and Tips

Age is the headline risk. Last release 2018 means it was authored against the Twig 1.x/2.x era. Twig 3 reworked the parser and node compiler internals that this extension hooks into, so the arrow syntax may fail to parse or mis-compile. Pin Twig and prove compatibility in a throwaway branch before you depend on it. If it breaks, budget to fork and modernize the extension yourself — the codebase is small.

Parse-time, not runtime. The => syntax is not a function call the VM interprets; the extension rewrites it during parsing. Errors therefore surface as "Unexpected token" compile exceptions, not catchable runtime exceptions. Clear the Twig cache (php artisan twig:clear, or delete storage/framework/views / var/cache) after changing the extension registration, or you will debug stale compiled templates.

Cache and registration order. The extension must be added before the first template compiles. Registering it lazily (e.g., in a controller) leaves previously cached templates compiled without arrow support. Always clear the compiled cache after deploying a registration change.

Twig sandbox / security. Arrow functions compile to real PHP closures, which sidesteps Twig's normal sandbox restrictions if you expose user-authored templates. Treat any template source that uses lambdas as trusted code — do not allow end users to supply it.

Closure scope. Captured variables are resolved against the template context at invocation, not at definition; a value changed later in the template can change what the lambda sees. Keep lambdas self-contained (operate on their parameters and literal values) to avoid spooky action at a distance.

Blade confusion. If the project is genuinely Blade-based, this package buys you nothing — there is no Blade bridge. Equivalent work belongs in controller/Collection methods or a view composer. Recommend it only when the stack is actually Twig.

Performance. Each lambda becomes a PHP closure per template render; for large datasets the pipe chain reallocates arrays at each step. If a template maps/filters thousands of rows, push the operation into the controller or a custom Twig function so it can be optimized and cached once.

Extension points. If a built-in filter is missing in your version, subclass LambdaExtension and register additional TwigFilter instances that accept a \Closure; the arrow syntax gives you a callable, so any custom filter taking a callable slots in. This is the cleanest escape hatch and often better than forking the filters.

Debugging arrow syntax. Strip the pipeline down to the smallest failing expression (e.g., [1]|map(x => x)), confirm it compiles, then re-add filters one at a time. Syntax problems with multi-parameter lambdas (parentheses, spaces, default values) are the most common source of confusing template errors.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
novasa/laravel-language-center
opencage/geocode
adolfoholzer/parameters
livenetworks/ln-starter
shitoudev/permissionmanager
johannesclimacus/laravel-tui
hocvt/seotools
vitalybaev/sypexgeo
amphibee/themosis-ignition
gito-me/fast-excel
frankyso/laravel-ipaymu
geolize-studio/laravel-chile
boomerangui/chat
jinas/dhivatar
store-doc/laravel-storage-driver
plus-it/laravel-translation-manager
diephp/perhaps
diephp/telegraph
osmaviation/spreadsheet
microsoft/fluentui-system-icons