检查变量是 Twig 中的字符串还是数组 [英] Check if variable is string or array in Twig
本文介绍了检查变量是 Twig 中的字符串还是数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在 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
这篇关于检查变量是 Twig 中的字符串还是数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文