How to create a ul - li menu from a tree like array?

前端 未结 3 1323
醉酒成梦
醉酒成梦 2021-01-06 09:52

I have an array with title and children index.

title is always not-null. children is an array, empty or not-empt

3条回答
  •  有刺的猬
    2021-01-06 10:26

    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

提交回复
热议问题