TWIG:已定义且不为空

TWIG: is defined and is not null

快速提问 我有一个 var,我想检查它是否已定义(以避免在渲染中出现错误)以及它是否不为 null(如果为 null,则显示带有 Else 的内容)

{% if var is not null %} 有效

{% if var is defined %} 有效

{% if var is not null and is defined %} 不起作用 知道正确的语法吗?

编辑 解决方法是:

{% if var is defined %}
    {% if var is not null %}
        {{ var }}
    {% else %}
        blabla
    {% endif %}
{% endif %}

很多简单的代码...如何合并两个 IF 的想法?

您需要在每次检查中声明变量,因此 {% if var is defined and var is not null %}

错误

{% if var is not null and var is defined %}

这不起作用,因为在 twig 中定义了一个 null 的变量,但是如果您先检查 null 而它未定义,则会引发错误。

正确

{% if var is defined and var is not null %}

这会起作用,因为我们首先检查它是否被定义,如果没有定义则放弃。只有定义了变量,我们才会检查它是否为空。

就像任何其他编程语言一样,您仍然需要在每次检查时引用变量。

{% if var is defined and not null %}

这是行不通的,因为在检查定义后,twig 不知道您要检查的内容是否为空。解决方案:

{% if (var is defined) and (var is not null) %}
... code
{% endif}

括号不是必需的。它更倾向于可读性。希望对您有所帮助。

我一直用??运算符在我知道可能未定义变量时提供 'default' 值。所以 {% if (var is defined and var is not null) %} 等同于:

{% if (var ?? null) is not null %}

如果您只想检查一个可能未定义的值是否为真,您可以这样做:

{% if (var ?? null) %}

我用这个稍微短一点的。它不是 100% 等于 null 测试,但它适合我的使用。

{% if var is defined and var %}

这可能是您要检查的内容的最短语法

{% if var ?? false %}