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

Array comparisons (`in` and `==`) do not conform to TwigPHP

Open dorian-marchal opened this issue 4 years ago • 3 comments

in operator doesn't work like Twig PHP when comparing arrays

For example, this evaluates to "true" with Twig PHP but "false" with twig.js:

{{ ["foo", "bar"] in [['foo', 'bar'], ['qux', 'baz']] ? 'true' : 'false' }}

This falls in this test: https://github.com/twigjs/twig.js/blob/788437f0066696599b2f0a2f5fad791d0ee0ff31/src/twig.expression.operator.js#L20-L23

indexOf is not undefined for arrays.

Also, == operator is broken with array (it only seems to compare array lengths):

{{ ['foo'] == ['bar'] ? 'true' : 'false' }}

Evaluates to "true" with twig.js but "false" with Twig PHP.

This time, I think the corresponding code is here: https://github.com/twigjs/twig.js/blob/788437f0066696599b2f0a2f5fad791d0ee0ff31/src/twig.expression.operator.js#L170-L178

dorian-marchal avatar Dec 11 '19 15:12 dorian-marchal

Twig.js doesn't support Twig comparison rules. They are quite complex (and arguably debatable) because Twig inherits them from PHP.

ericmorand avatar Dec 14 '19 07:12 ericmorand

OK, I understand.

To me this is not only a compatibility issue between Twig JS and Twig PHP. This kind of array comparison helps to write more concise templates:

{# For example: #}
{% if [country, city, place] in [
  ["France", "Paris", "Palais de l'Élysée"],
  ["Germany", "Berlin", "Federal Chancellery"],
  ...
] %}
    Official residence
{% endif %}

{# instead of: #}
{% if
    (country == "France" and city == "Paris" and place == "Palais de l'Élysée")
    or (country == "Germany" and city == "Berlin" and place == "Federal Chancellery")
    ...
%}
    Official residence
{% endif %}

I suppose I could give an other try to Twing but it is really heavy and I need it on client side.

dorian-marchal avatar Dec 14 '19 11:12 dorian-marchal