https://github.com/gglnx/twig-empty-coalesce
The empty test and default filter as an operator
https://github.com/gglnx/twig-empty-coalesce
twig twig-extension twig-syntax
Last synced: 5 months ago
JSON representation
The empty test and default filter as an operator
- Host: GitHub
- URL: https://github.com/gglnx/twig-empty-coalesce
- Owner: gglnx
- License: mit
- Created: 2022-01-05T16:52:22.000Z (over 4 years ago)
- Default Branch: main
- Last Pushed: 2022-01-12T10:57:16.000Z (over 4 years ago)
- Last Synced: 2025-12-20T07:52:31.158Z (6 months ago)
- Topics: twig, twig-extension, twig-syntax
- Language: PHP
- Homepage:
- Size: 4.88 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# Empty Coalesce Operator for Twig
[](https://packagist.org/packages/gglnx/twig-empty-coalesce)
This library adds a new [operator expression](https://twig.symfony.com/doc/2.x/templates.html#expressions) to Twig with three question marks (`???`) to check if the left value is defined, not null and not empty. Works the same way as the [`empty` test](https://twig.symfony.com/doc/2.x/tests/empty.html) and the `|default` filter.
```twig
{% set _null = null %}
{% set _empty = '' %}
{# Null Coalesce: Output will be string(0) "" because _empty is defined and not exactly null #}
{{ dump(_undefined ?? _null ?? _empty ?? 'fallback') }}
{# Default Filter: Output will be string(8) "fallback" because _empty is defined, but an empty string #}
{{ dump(_undefined | default(_null | default(_empty | default('fallback')))) }}
{# Same as the default filter, but much more readable #}
{{ dump(_undefined ??? _null ??? _empty ??? 'fallback') }}
```
## Requirements
* Twig >=2.14 and Twig >=3.0
* PHP >=7.4
## Installation
The recommended way to install this loader is via [Composer](https://getcomposer.org/):
```bash
composer require gglnx/twig-empty-coalesce
```
You can install this library as extension in:
```php
require_once '/path/to/vendor/autoload.php';
$twig = new \Twig\Environment($loader);
$twig->addExtension(new \Gglnx\TwigEmptyCoalesce\Extension\EmptyCoalesceExtension());
```