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 ?
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 ).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With