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