【发布时间】:2011-03-16 22:42:22
【问题描述】:
我应该使用什么构造来检查 Twig 模板中的值是否为 NULL?
【问题讨论】:
标签: php twig short-circuiting
我应该使用什么构造来检查 Twig 模板中的值是否为 NULL?
【问题讨论】:
标签: php twig short-circuiting
取决于你到底需要什么:
is null 检查值是否为null:
{% if var is null %}
{# do something #}
{% endif %}
is defined检查变量是否定义:
{% if var is not defined %}
{# do something #}
{% endif %}
此外,对两个值进行类型严格比较的 is sameas 测试可能对检查 null 以外的值(如 false)感兴趣:
{% if var is sameas(false) %}
{# do something %}
{% endif %}
【讨论】:
{% if var is not null %}
isset() 函数不同,is defined 将返回 true 如果定义了一个变量并且它的值为空。
is_ sameas 之类的值,必须是 {% if var is same as(false) %} 而不是 {% if var is sameas(false) %} 参见文档 url => twig.symfony.com/doc/2.x/tests/sameas.html
如何在 twig 中设置默认值:http://twig.sensiolabs.org/doc/filters/default.html
{{ my_var | default("my_var doesn't exist") }}
或者如果你不希望它在 null 时显示:
{{ my_var | default("") }}
【讨论】:
undefined or empty和null有区别吗?
没有任何假设,答案是:
{% if var is null %}
但这只有在var 正好是NULL 时才会成立,而不是任何其他计算结果为false 的值(例如零、空字符串和空数组)。此外,如果没有定义var,也会导致错误。更安全的方法是:
{% if var is not defined or var is null %}
可以简写为:
{% if var|default is null %}
如果您不向 default 过滤器提供参数,则它假定为 NULL(某种默认默认值)。所以检查变量是否为空(null、false、空字符串/数组等)的最短和最安全的方法(我知道):
{% if var|default is empty %}
【讨论】:
我不认为你可以。这是因为如果在 twig 模板中未定义(未设置)变量,它看起来像 NULL 或 none(在 twig 术语中)。我很确定这是为了抑制模板中出现错误的访问错误。
由于 Twig (===) 中缺少“身份”,这是你能做的最好的事情
{% if var == null %}
stuff in here
{% endif %}
翻译为:
if ((isset($context['somethingnull']) ? $context['somethingnull'] : null) == null)
{
echo "stuff in here";
}
如果你擅长 type juggling,则意味着 0、''、FALSE、NULL 和未定义的 var 之类的东西也会使该陈述成立。
我的建议是要求将身份实现到 Twig 中。
【讨论】:
{if var is none} 比较合适,PHP 的等价物是什么?
{% if abcxyz is none %} 变为 if (isset($context["abcxyz"])) { $_abcxyz_ = $context["abcxyz"]; } else { $_abcxyz_ = null; } if ((null === $_abcxyz_)) { echo "hi"; }。所以基本上如果值是 undefined 或 null,它会是真的。
none 是null ref 的别名。
{% if var is empty %} twig.sensiolabs.org/doc/tests/empty.html 转换为PHP if (empty($var)) 评估虚假值(!isset, null, 0, array(), "", false, "0", 0.0)php.net/manual/en/function.empty.php 你也可以使用@ 987654344@ 用于身份 (===)。 twig.sensiolabs.org/doc/tests/sameas.html
你也可以使用一行来做到这一点:
{{ yourVariable is not defined ? "Not Assigned" : "Assigned" }}
【讨论】:
//test if varibale exist
{% if var is defined %}
//todo
{% endif %}
//test if variable is not null
{% if var is not null %}
//todo
{% endif %}
【讨论】:
if var is not null。
您可以使用以下代码来检查是否
{% if var is defined %}
var is variable is SET
{% endif %}
【讨论】:
此外,如果您的变量是 ARRAY,那么选项也很少:
{% if arrayVariable[0] is defined %}
#if variable is not null#
{% endif %}
或
{% if arrayVariable|length > 0 %}
#if variable is not null#
{% endif %}
这仅适用于您的数组 is defined AND 为 NULL
【讨论】: