问题
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