Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if variable is string or array in Twig

Tags:

twig

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 ?

like image 757
hsz Avatar asked Dec 14 '12 09:12

hsz


People also ask

How do you check variables in twig?

By setting strict_variables to false If set to false , Twig will silently ignore invalid variables (variables and or attributes/methods that do not exist) and replace them with a null value. When set to true , Twig throws an exception instead (default to false ).


1 Answers

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

{# evaluates to true if the users 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

like image 152
DarkBee Avatar answered Sep 18 '22 15:09

DarkBee