felds / twig-extra
Custom Twig tags and extensions (switch tag).
Installs: 0
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/felds/twig-extra
Requires
- php: >=8.4
- twig/twig: ^3.22
Requires (Dev)
- phpunit/phpunit: ^12.5
This package is auto-updated.
Last update: 2026-01-22 00:19:38 UTC
README
Custom Twig extras for Twig 3.22+ and PHP 8.4+:
switchtag?.nullsafe operator
Installation
composer require felds/twig-extra
Usage
Register the desired extensions with Twig:
$twig->addExtension(new \Felds\TwigExtra\SwitchExtension()); $twig->addExtension(new \Felds\TwigExtra\NullsafeExtension());
In Symfony, you can let autoconfigure pick it up by registering the services:
# services.yaml Felds\TwigExtra\SwitchExtension: ~ Felds\TwigExtra\NullsafeExtension: ~
Switch tag ({% switch %})
Match a value against multiple comparisons, picking the first case that evaluates truthy:
{% switch value %}
{% case 1 %} exactly 1
{% case == 2 %} exactly 2
{% case > 1 %} More than 1
{% default %} Other
{% endswitch %}
- Supports all Twig comparison operators (==, !=, >, <, >=, <=,
is same as,in,not in,matches,starts with,ends with, etc.). - Cases are evaluated top-down; the first hit wins, otherwise
defaultruns when present. - The switch value is stored internally and the original context is restored after the block.
Nullsafe operator (?.)
Access attributes and call methods without throwing when the left side is null or missing:
{{ user?.name }}
{{ post?.author?.getName() }}
{{ date?.format('Y-m-d') ?? 'no date' }}
- If the base value is null or undefined, the chain short-circuits to null.
- Works with arrays, objects, property fetches, and method calls.
- Respects strict variables (nullsafe short-circuits instead of raising).
Tests
composer install ./vendor/bin/phpunit tests
License
MIT
Changelog
See CHANGELOG.md.