快速问题我有一个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)
这将起作用,因为我们检查它是否是第一个定义的,并且在没有的时候会出现.只有定义了变量,我们才检查它是否为空.
我一直用的是?? 当我知道可能未定义变量时,运算符提供“默认”值。所以{% 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)
| 归档时间: |
|
| 查看次数: |
20744 次 |
| 最近记录: |