twig.js
twig.js copied to clipboard
strict_variables evaluating both operands of the and operator
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.
I confirm that TwigPHP "and" token only evaluates the right operand if the left one is false.
Can you link to an example on twigfiddle?
@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.
same problem here
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.
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.
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.