Check if variable is string or array in Twig

hsz picture hsz · Dec 14, 2012 · Viewed 69.6k times · Source

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

Expected solution:

messages.en.yml:

hello:
  stranger: Hello stranger !
  known: Hello %name% !

Twig template:

{% set title='hello.stranger' %}
{% set title=['hello.known',{'%name%' : 'hsz'}] %}

{% if title is string %}
  {{ title|trans }}
{% else %}
  {{ title[0]|trans(title[1]) }}
{% endif %}

Is it possible to do it this way ? Or maybe you have better solution ?

Answer

DarkBee picture DarkBee · Jul 30, 2013

Can be done with the test iterable, added in twig1.7, as Wouter J stated in the comment :

{# evaluates to true if the foo variable is iterable #}
{% if users is iterable %}
    {% for user in users %}
        Hello {{ user }}!
    {% endfor %}
{% else %}
    {# users is probably a string #}
    Hello {{ users }}!
{% endif %}

Reference : iterable