twig.js icon indicating copy to clipboard operation
twig.js copied to clipboard

strict_variables evaluating both operands of the and operator

Open BrianWalters opened this issue 6 years ago • 7 comments

I am using twig.js with strict_variables set to true.

If I have a template like this:

{% if pagination|default and pagination.links|default %}
    ...
{% endif %}

and I loaded it with a completely empty context, I would expect no errors. This works in PHP Twig and what is recommended.

In twig.js, I get a TwigException:

Can't access a key links on an null or undefined object.

It looks to me that twig.js is evaluating the truthiness of both operands even if the first one is false. I would not expect this, not only for this use case, but because JavaScript doesn't work this way either.

The workaround is this:

{% if pagination|default %}
    {% if pagination.links|default %}
        ...
    {% endif %}
{% endif %}

That makes the template harder to read and creates more indenting and whitespace then normal.

BrianWalters avatar Jun 29 '19 15:06 BrianWalters

I confirm that TwigPHP "and" token only evaluates the right operand if the left one is false.

ericmorand avatar Jun 30 '19 01:06 ericmorand

Can you link to an example on twigfiddle?

willrowe avatar Jul 01 '19 15:07 willrowe

@willrowe https://twigfiddle.com/3yjwsw

My example above in a twigfiddle. The exception I get in twig.js is:

TwigException: Can't access a key links on an null or undefined object.

BrianWalters avatar Jul 03 '19 17:07 BrianWalters

same problem here

axten avatar Oct 27 '19 22:10 axten

Same error when explicitly checking a undefined variable. Following template should always run even if lie isn't defined and strict_variables is enabled - just the output should change: The {{ baked_good }} is a{% if lie is defined and lie %} lie {% else %} reality {% endif %}!

However, with strict_variables enabled it fails with TwigException: Variable "lie" does not exist. Running Example: https://jsfiddle.net/jsz9uy3h/6/

Interestingly if you use https://cdn.jsdelivr.net/npm/[email protected]/twig.min.js in above fiddle it works. Looks like there's somewhere a regression.

das-peter avatar Nov 18 '19 23:11 das-peter

After further evaluation I suspect my comment above points to a different issue as it seem like the regression was just recently introduced - I created a dedicated issue for it: #679 Sorry for the noise here.

das-peter avatar Nov 18 '19 23:11 das-peter

I can confirm this is not working as expected, see this example: https://codepen.io/willrowe/pen/eYMeWqx

However, it does not appear to be for the reasons originally outlined. The current version of twig.js throws the error: TwigException: Variable 'pagination' does not exist.. So it appears to be hitting an issue with the default filter before even making it to the and.

willrowe avatar Jul 28 '22 20:07 willrowe