Skip to content

`is iterable` test on `null` or `undefined` values results in incorrect behavior

The is iterable test doesn't always give correct results for values that are null or undefined.

null

In Twing, the following code that defines x as null via a set block doesn't error out (it prints "null is not iterable"):

{% set x %}
  {{ null }}
{% endset %}
{% if x is iterable %}null is iterable{% else %}{{ x }}null is not iterable{% endif %}

whereas the following code that defines x as null via a set "one-liner" errors out with "object null is not iterable":

{% set x = null %}
{% if x is iterable %}null is iterable{% else %}null is not iterable{% endif %}

Passing in x: null from the JavaScript results in the same error.

In TwigPHP, there is no error when checking if null is iterable (it simply resolves to false). So the set-block behavior seems to be correct, and I think that the error that results from the set one-liner or from passing in a null value from the JavaScript is a bug.

undefined (and missing / not-defined)

Relatedly (though less important), checking if an undefined value is iterable throws the "wrong" error. In TwigPHP, you get a helpful "does not exist" runtime error. In Twing, you get a JavaScript "undefined is not iterable (cannot read property Symbol(Symbol.iterator))" error, which is less helpful.

Relatedly, checking if an undefined value is iterable in Twing throws a JavaScript "cannot read property Symbol(Symbol.iterator)" error, which isn't reflective of what happens in TwigPHP for values that haven't been defined. The correct behavior is:

  • if strict_variables is enabled, throw a "does not exist" runtime error;
  • if strict_variables is disabled (the default), treat the undefined case the same as the null case.
Edited by Michael Warner
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information