Search code examples
menusubmenuwagtail

How to add multi-level menu support to wagtail (with support for non-wagtail based pages)


How can I add support for custom menus which will work also with non-Wagtail based pages.

  1. For example by giving directly a relative url to a registration page such as '/account/registration')
  2. For example by giving directly an absolute url to an external page such as 'www.stackoverflow.com'

I found this very interesting project: https://github.com/rkhleics/wagtailmenus Unfortunately is does not support submenus in the main menu.


Solution

  • One thing about Wagtail is that what I would call the data tree is made up only of pages (it's called a page tree). This tree is used as the basis for navigation but, of course, sometimes you might want a navigation item in this tree to be something other than a page. I accomplish what you want to do by subclassing Page:

    from django.http import HttpResponseRedirect
    
    class Node(Page):
    
        subpage_types = [your subpage types]
        parent_page_types = [your parent page types]
    
        link = models.CharField(max_length=255, default='', blank='True')
    
        content_panels = Page.content_panels + [
            FieldPanel('link')
        ]    
    
        def serve(self, request):
            if self.link is not None:
                return HttpResponseRedirect(self.link)
            else:
                pass
    

    And in the template:

    {% for item in menu_items %}
        <li>
            <a href="{% if item.specific.link and item.specific.link != '' %}{{ item.specific.link }}{% else %}{% pageurl item %}{% endif %}">{{ item.title }
            </a>
        </li>
    {% endfor %}