henrik
henrik

Reputation: 71

How to create a dynamic menu structure with Django?

I want a menu structure with a menu and a submenu, and depending on what page is currently viewed, I want to highlight items in both menus. Are there any modules or apps that provide this? If not, what would be the best way to approach the problem?

Upvotes: 7

Views: 8565

Answers (2)

Tomasz Zieliński
Tomasz Zieliński

Reputation: 16346

Quick google search gives this:

https://github.com/jphalip/django-treemenus

http://code.google.com/p/django-menuse/

You can also create such simple menu manually, just pass to the template list of menu items, active menu and list of submenu items for the active menu and the active submenu item:

     <ul>
     {% for item in menu_items %}
         <li>
         {% if item.id == active_menu_item %}
             <span class="active-menu-item">{{ item }}</span>
             <ul>
                   {# Similar code for submenu items #}
             </ul>
         {% else %}
             <a class="inactive-menu-item" href="{{ item.url }}">{{ item }}</a>
         {% endif %}
         </li>
     {% endfor %}
     </ul>

Upvotes: 6

Yaroslav Nikitenko
Yaroslav Nikitenko

Reputation: 1843

According to djangopackages, the most popular menu application in 2018 is django-sitetree.

Item highlighting can be done with the second tool from the link above, django-activeurl.

For large sites, however, django-sitetree may have performance issues.

There is another way which is related to the hierarchical structure of menus: modified preorder tree traversal, which optimizes database queries for tree lookups.

Use django-mptt to store hierarchical data (such as menus with submenus to unlimited depth). Use django-mptt-admin to easily manage them in admin menu. contenttypes framework may be useful for more generic menus (this is not shown in django-mptt tutorial).

Upvotes: 1

Related Questions