Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of is_array in Twig

Tags:

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
like image 467
Goldentoa11 Avatar asked Oct 30 '13 20:10

Goldentoa11


2 Answers

Another way :

{% if my_var.count()>1 %}
like image 118
BENARD Patrick Avatar answered Sep 19 '22 04:09

BENARD Patrick


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 %}
like image 25
André Figueira Avatar answered Sep 19 '22 04:09

André Figueira