Django CMS Multi-Level Dropdown Menu

早过忘川 提交于 2019-12-05 16:43:59

WOHO! I finally did it!

base.html

<div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
        {% show_menu 0 100 100 100 "menu.html" %}
    </ul>
</div>

menu.html:

{% for child in children %}
    <li class="child{% if child.selected %} selected{% endif %}{% if child.ancestor %} ancestor{% endif %}{% if child.sibling %} sibling{% endif %}{% if child.descendant %} descendant{% endif %}{% if child.children %} dropdown{% endif %}">

        <a {% if child.children %}class="dropdown-toggle" data-toggle="dropdown"{% endif %} href="{{ child.attr.redirect_url|default:child.get_absolute_url }}">
            <span>{{ child.get_menu_title }}</span>{% if child.children|length %}<span class="caret"></span>{% endif %}
        </a>

        {% if child.children %}
            <ul class="dropdown-menu multi-level" role="menu" aria-labelledby="dropdownMenu">
                {% show_menu from_level to_level extra_inactive extra_active "dropdownmenu.html" "" "" child %}
            </ul>
        {% endif %}

    </li>
    {% if class and forloop.last and not forloop.parentloop %}{% endif %}

{% endfor %}

and my dropdownmenu.html: (The recursive stuff starts here)

{% load i18n menu_tags cache mptt_tags %}
{% for child in children %}
    <li {% if child.children %}class="dropdown-submenu"{% else %} {% endif %}>
        <a tabindex="-1" href="{{ child.attr.redirect_url|default:child.get_absolute_url }}">{{ child.get_menu_title }}</a>
        {% if child.children %}
            <ul class="dropdown-menu">
                {% show_menu from_level to_level extra_inactive extra_active "dropdownmenu.html" "" "" child %}
            </ul>
        {% endif %}

    </li>
{% endfor %}

and the most important, menu.py:

class TopicsSubMenu(CMSAttachMenu):
    name = _("Wiki Sub-Menu")

    def get_nodes(self, request):
        nodes = []
        categories = Category.objects.all()

        for c in categories:
            node = NavigationNode(
                mark_safe(c.name),
                c.get_absolute_url(),
                c.pk
            )
            if c.parent:
                node.parent_id = c.parent_id
            nodes.append(node)

        topics = Topic.objects.all().exclude(category__isnull=True)
        for t in topics:
            node = NavigationNode(
                mark_safe(t.title),
                t.get_absolute_url(),
                t.pk,
                t.category.all()[0].id,
                parent_namespace="TopicsSubMenu"
            )
            nodes.append(node)
        return nodes

menu_pool.register_menu(TopicsSubMenu)

And thats it!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!