快速提问
我有一个 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 not null and var is defined %}
这是行不通的,因为在 twig 中定义了一个为 null 的变量,但是如果您首先检查 null 并且未定义它,则会引发错误。
正确
{% if var is defined and var is not null %}
这会起作用,因为我们首先检查它是否已定义,否则将中止。只有当变量被定义时,我们才检查它是否为空。
关于symfony - TWIG:已定义且不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31314592/