Skip to content

Instantly share code, notes, and snippets.

@zerolab
Last active February 24, 2020 22:45
Show Gist options
  • Save zerolab/fcbb9e71fd646163411352b871e152f3 to your computer and use it in GitHub Desktop.
Save zerolab/fcbb9e71fd646163411352b871e152f3 to your computer and use it in GitHub Desktop.
Wagtail "native" menus
# myapp/templates/tags/menu_children.html
{% load wagtailcore_tags %}
<ul class="primary-children">
{% for child in menuitems_children %}
<li{% if child.is_active %} class="active"{% endif %}><a href="{% pageurl child %}">{{ child.title }}</a></li>
{% endfor %}
</ul>
# myapp/templates/tags/menu_primary.html
{% load wagtailcore_tags myapp_tags %}
<ul class="primary">
<li>
<a href="{% pageurl request.site.root_page %}" title="home">Home</a>
</li>
{% for menuitem in menuitems %}
<li{% if menuitem.is_active %} class="active"{% endif %}>
<a href="{% pageurl menuitem %}">{{ menuitem.title }}</a>
{% if menuitem.has_children %}
{% menu_children parent=menuitem %}
{% endif %}
</li>
{% endfor %}
</ul>
# myapp/templatetags/myapp_tags.py
from django import template
register = template.Library()
def has_menu_children(page):
if page.get_children().live().in_menu():
return True
else:
return False
# Retrieves the top menu items - the immediate children of the parent page
# The has_menu_children method is necessary because the bootstrap menu requires
# a dropdown class to be applied to a parent
@register.inclusion_tag('pds/tags/menu_primary.html', takes_context=True)
def menu_primary(context, parent=None):
menuitems = parent.get_children().live().in_menu()
# Use get_navigation_menu_items() ?
for menuitem in menuitems:
menuitem.has_children = has_menu_children(menuitem)
menuitem.is_active = False
if context['request'].path.startswith(menuitem.url):
menuitem.is_active = True
return {
'menuitems': menuitems,
# required by the pageurl tag that we want to use within this template
'request': context['request'],
}
# Retrieves the children of the top menu items for the drop downs
@register.inclusion_tag('myapp/tags/menu_children.html', takes_context=True)
def menu_children(context, parent):
menuitems_children = parent.get_children().live().in_menu()
for menuitem in menuitems_children:
menuitem.is_active = False
if context['request'].path.startswith(menuitem.url):
menuitem.is_active = True
return {
'parent': parent,
'menuitems_children': menuitems_children,
# required by the pageurl tag that we want to use within this template
'request': context['request'],
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment