0

I have a problem, in Controller I have a multidimensional array, but I don't know how many dimensional this array is. It is dynamically and determined by database, so can I put it to twig in any way?

When I'm using function dump in twig, it displays:

array(5) { 
  [0]=> int(50) 
  [1]=> int(51) 
  [2]=> int(52) 
  [51]=> array(2) { 
    [0]=> int(55) 
    [55]=> array(1) { 
      [0]=> int(56) 
    } 
  } 
  [52]=> array(2) { 
    [0]=> int(53) 
    [1]=> int(54) 
  } 
} 

1 Answer 1

4

Okay, you can do that like this: (if you know your array has only one more dimension, total 2 dimensions).

{% for key, item in items %}
    {% if item is iterable %}
        {% for sub_item in item %}
            Do something...
        {% endfor %}
    {% else %}
        Do something else...
    {% endif %}
{% endfor %}

If you have a multidimensional array that has more than 1 sub array, you have to call a function recursively to reach that other sub dimensions. You can do it in your twig extension file.

A recursive function is calling itself to reach sub items in a multidimensional array. I don't know what do you want to do with that array but i'm gonna make a basic function depends on your array.

function recursiveTwig($array)
{
    foreach($array as $key => $value){
        if(is_array($key)) {
            $this->recursiveTwig($key);
        } else {
            //Do something with your value...
        }
    }
}

Macro:

How to render a tree in Twig

Sign up to request clarification or add additional context in comments.

2 Comments

Nope. you can use it in your twig_extension file. symfony.com/doc/current/cookbook/templating/twig_extension.html but if you want to do it with macros, you can set a macro in a twig file and include it.
thank you very much, it works :) I use macro, I think it's a better way

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.