Do Twig's logical operators evaluate both expressions?

前端 未结 1 377
别那么骄傲
别那么骄傲 2021-01-22 20:48

If I use a Twig expression like:

{% if a and function(a) %}

with a being falsey, does Twig still evaluate function(a)

相关标签:
1条回答
  • 2021-01-22 21:28

    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.

    As pointed out by zerkms, this is testable by using die.

    For example:

    {% if water_is_dry and die('water_is_wet') %}
    

    will not die, since the first expression, being null, is falsey.

    Whereas:

    {% if water_is_dry or die('water_is_wet') %}
    

    will die.

    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'));
    
    0 讨论(0)
提交回复
热议问题