TWIG:已定义且不为空

Rap*_*l_b 9 symfony twig

快速问题我有一个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 %}
Run Code Online (Sandbox Code Playgroud)

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

osh*_*ell 21

错误

{% if var is not null and var is defined %}
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为在twig中为null的变量是定义的,但是如果先检查null并且未定义它,则会抛出错误.

正确

{% if var is defined and var is not null %}
Run Code Online (Sandbox Code Playgroud)

这将起作用,因为我们检查它是否是第一个定义的,并且在没有的时候会出现.只有定义了变量,我们才检查它是否为空.

  • 为了完整起见,值得一提的是,您必须在每个语句中都引用var,您在回答中做了此操作,但是OP在他的代码中没有做过(如果var不为null,他写了{%并定义为%}`) (2认同)

Dan*_*ard 7

我一直用的是?? 当我知道可能未定义变量时,运算符提供“默认”值。所以{% if (var is defined and var is not null) %}相当于:

{% if (var ?? null) is not null %}
Run Code Online (Sandbox Code Playgroud)

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

{% if (var ?? null) %}
Run Code Online (Sandbox Code Playgroud)


qoo*_*mao 5

您需要在每个检查中声明var {% if var is defined and var is not null %}.