Goldentoa11
Goldentoa11

Reputation: 1760

Equivalent of is_array in Twig

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

Upvotes: 5

Views: 7366

Answers (3)

Raja Khoury
Raja Khoury

Reputation: 3195

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 %}

Upvotes: 4

André Figueira
André Figueira

Reputation: 6736

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 %}

Upvotes: 3

BENARD Patrick
BENARD Patrick

Reputation: 31005

Another way :

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

Upvotes: 4

Related Questions