Twig 的逻辑运算符是否评估这两个表达式?
如果我使用 Twig 表达式,例如:
If I use a Twig expression like:
{% if a and function(a) %}
如果 a
为假,Twig 是否仍会评估 function(a)
,或者表达式是否会评估为 false
而不会评估第二部分?或
也是如此.
with a
being falsey, does Twig still evaluate function(a)
, or will the expression evaluate to false
without evaluating the second part? Likewise with or
.
推荐答案
tl;dr:如果第一部分为假,Twig 的逻辑运算符不会计算and"表达式的第二部分,同样,如果第一部分是真实的.
tl;dr: Twig's logical operators do not evaluate the second part of an 'and' expression if the first part is falsey, likewise with 'or' if the first part is truthy.
正如 zerkms 指出的,这是可测试的通过使用模具.
As pointed out by zerkms, this is testable by using die.
例如:
{% if water_is_dry and die('water_is_wet') %}
不会死,因为第一个表达式为空,是假的.
will not die, since the first expression, being null, is falsey.
鉴于:
{% if water_is_dry or die('water_is_wet') %}
会死的.
请注意,这仅在您将 die 作为函数添加到 Twig 实例时才有效,如下所示:
Note, that this works only if you add die as a function to your Twig instance, like so:
$twig->addFunction(new Twig_SimpleFunction('die', 'die'));
相关文章