是否可以在 Twig
中检查给定变量是否为字符串?
Is it possible to check if given variable is string in Twig
?
预期的解决方案:
messages.en.yml
:
hello:
stranger: Hello stranger !
known: Hello %name% !
Twig
模板:
{% 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 ?
可以通过测试 iterable
来完成,添加在 twig1.7 中,正如 Wouter J 在评论中所说:
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 %}
参考:iterable