[Answer]-Django recursive menu

0👍

You have two errors. Firstly you should be iterating through child.children.all, not chil..., and secondly that final loop needs to be moved inside the second one.

1👍

Here is the easiest solution in my opinion:

First of all, create some ‘recursive_menu.html’ template and put this code:

<li>{{ category.title }}
        <ul>
            {% if category.children %}
                {% for child in category.children.all %}
                    {%with category=child template_name="shop/recursive_menu.html" %}
                       {%include template_name%}
                    {%endwith%}
                {% endfor %}
            {% endif %}
        </ul>
    </li>

As the same time your base template looks like:

<ul>
{% for category in categories %}
     {% include "shop/recursive_menu.html" %}
{% endfor %}
</ul>

Explanation:

  1. Code iterates through all of the category items in root ‘categories’.
  2. Outputs each category and associated layout.
  3. If the category has children:

    • Set the category variable as the children of the current categories.
    • Recursive call to current template file.
    • Output any nested children in a nested list.
    • Repeat recursion as necessary.

Result looks like this:

enter image description here

Leave a comment