Search code examples
arraysobjecttwig

How can I find out if my variable is an object or an array with twig?


I try to find out if my variable is an object or an array:

{% if variable is iterable %}It is an array{% else %}it is an object{% endif %}

But in cases I get the result:

It is an array

Solution

  • You are correct, the twig iterable test has shortcomings, since objects can be iterable as well. PHP has handy functions like is_array and is_object, however, it is not possible to access regular PHP function in Twig directly. So, we need to write a Twig extension/Test, i.e. add a new Twig_SimpleTest to check if an item is_array. You can add this test to your app configuration after the general twig bootstrap.

    $isArray= new Twig_SimpleTest('array', function ($value) {
        return is_array($value);
    });
    $twig->addTest($isArray);
    

    and simply us it like this:

    {% if var is array%} It is an array
    {% else %} It is an object{% endif %}