Equivalent of is_array in Twig

老子叫甜甜 提交于 2021-02-04 18:09:45

问题


I'm working on a template and I need to check if something is an array. How do I do that in Twig?

I've tried

{% if my_var is iterable %}
  {% for v in my_var %}
      ...
  {% endfor %}
{% else %}
  {{ my_var }}
{% endif %}

but it always prints my_var, even when my_var is really an array, as evidenced when it prints out

Array
Array
myusername
../data/table.sqlite3

回答1:


Another way :

{% if my_var.count()>1 %}



回答2:


Just add a custom filter:

$twig->addFilter('is_array', new \Twig_Filter_Function('is_array'));

Then use it like this:

{% if my_var|is_array %}



回答3:


If you don't want to create a custom filter use iterable, as per the docs :

iterable checks if a variable is an array or a traversable object

{% if myVar is iterable %} ... {% endif %}


来源:https://stackoverflow.com/questions/19693500/equivalent-of-is-array-in-twig

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!