I have an array with title
and children
index.
title
is always not-null. children
is an array, empty or not-empt
I had to achieve something similar, yet I wanted the HTML generation to be in inside a twig template. This could look like this:
{% macro printMenuElements(nestedListElements, level = 0, parent = 'root') %}
{% for nestedElement in nestedListElements %}
{% set children = nestedElement.children %}
{% set title = nestedElement.title %}
{% if children is not empty and children is iterable %}
-
{{ title }}
{{ _self.printMenuElements(children, level +1, title) }}
{% else %}
-
{{ title }}
{% endif %}
{% endfor %}
{% endmacro %}
{% block body %}
Menu
{% import _self as helper %}
{{ helper.printMenuElements(yourArray) }}
{% endblock %}
Which generates an HTML output of:
-
N1
-
N11
-
N111
-
N2
-
N21