iliveinapark
iliveinapark

Reputation: 327

Do Twig's logical operators evaluate both expressions?

If I use a Twig expression like:

{% if a and function(a) %}

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.

Upvotes: 3

Views: 2906

Answers (1)

iliveinapark
iliveinapark

Reputation: 327

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'));

Upvotes: 6

Related Questions