felds/twig-extra
最新稳定版本:1.0.0
Composer 安装命令:
composer require felds/twig-extra
包简介
Custom Twig tags and extensions (switch tag).
README 文档
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.
统计信息
- 总下载量: 0
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 5
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-01-22