gglnx/twig-empty-coalesce

将空值测试和默认过滤器作为操作符

1.0.1 2022-01-12 10:57 UTC

This package is auto-updated.

Last update: 2024-09-12 16:42:29 UTC


README

Packagist

此库向Twig添加了一个新的操作符表达式,使用三个问号(???)来检查左边的值是否已定义、不为空且不为空字符串。与 empty 测试|default 过滤器的工作方式相同。

{% 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') }}

需求

  • Twig >=2.14 和 Twig >=3.0
  • PHP >=7.4

安装

建议通过 Composer 安装此加载器

composer require gglnx/twig-empty-coalesce

您可以将此库作为扩展安装

require_once '/path/to/vendor/autoload.php';

$twig = new \Twig\Environment($loader);
$twig->addExtension(new \Gglnx\TwigEmptyCoalesce\Extension\EmptyCoalesceExtension());