Check if variable is string or array in Twig

后端 未结 4 582
暗喜
暗喜 2020-12-24 10:29

Is it possible to check if given variable is string in Twig ?

Expected solution:

messages.en.yml:

hello:
  stranger         


        
4条回答
  •  不知归路
    2020-12-24 11:22

    I found iterable to not be good enough since other objects can also be iterable, and are clearly different than an array.

    Therefore adding a new Twig_SimpleTest to check if an item is_array is much more explicit. You can add this to your app configuration / after twig is bootstrapped.

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

    Usage becomes very clean:

    {% if value is array %}
        
    {% else %}
        
    {% endif % }
    

提交回复
热议问题