2
votes

To generate a simple menu, I can do:

<ul>
  {% for item in items %}
    <li>{{ item }}</li>
  {% endfor %}
</ul>

and then:

{% embed '...' with { items: ['Home', 'Articles'] %}

But how do I have to write the TWIG code, if I want to create endless deep menus like:

<ul>
  <li>Alpha</li>
  <li>Bravo</li>
    <ul>
      <li>Charlie</li>
      <li>Delta</li>
      <li>Echo</li>
        <ul>
          <li>Foxtrott</li>
        </ul>
      <li>Golf</ul>
    </ul>
  <li>Hotel</li>
  <li>India</li>
</ul>

Thx for help!

1

1 Answers

6
votes

To perform recursion in twig you can make use of macro's

{% import _self as macro %}

{{ macro.multilevel(foo) }}

{% macro multilevel(array) %}
    {% import _self as macro %}
    <ul>
    {% for item in array %}
        <li>
            {% if item is iterable %}
                {{ macro.multilevel(item) }}
            {% else %}
                {{ item }}
            {% endif %}
        </li>
    {% endfor %}
    </ul>    
{% endmacro %}

twigfiddle


EDIT With a simple array it's not possible to nest children in the same <li> as the parent. Herefor you would need to change your array arround,

Reformed array

$data = [
    'links' => [
        [
            'title'     => 'alpha',
            'href'      => 'http://www.alpha.com',
            'children'  => [],
        ],
        [
            'title'     => 'beta',
            'href'      => 'http://www.beta.com',
            'children'  => [
                [
                    'title'     => 'charlie',
                    'href'      => 'http://www.charlie.com',
                    'children'  => [],
                ],
                [
                    'title'     => 'delta',
                    'href'      => 'http://www.delta.com',
                    'children'  => [],
                ],
                [
                    'title'     => 'echo',
                    'href'      => 'http://www.echo.com',
                    'children'  => [
                        [
                            'title'     => 'foxtrot',
                            'href'      => 'http://www.foxtrot.com',
                            'children'  => [],
                        ],                      
                    ],
                ],              
            ],
        ],      
    ]   
];

tiwg

{% macro menu(links) %}
    {% import _self as macro %}
    <ul>
    {% for link in links %}
        <li>
            <a href="{{ link['href'] }}">{{ link['title'] }}</a>
            {% if not link['children']|default([]) is empty %}
                {{ macro.menu(link['children']) }}
            {% endif %}
        </li>
    {% endfor %}
    </ul>     
{% endmacro %}

twigfiddle