Reputation: 71
I'm trying to render a dynamic menu in Django/Wagtail. It works well so far but as I traverse the page tree and get to the last child, the menu disappears.
I'm wondering if there is a way to write the code so when a user has clicked through all the pages and reaches a page with no children, is it possible for me to get the siblings of that page and display those links instead of being blank? Or is there a way for me to tell wagtail that if the page has no children, render the siblings of the page?
This way someone can easily navigate the pages even if they are on a last child.
I'm using wagtailmenus to render a flat_menu to do this so far. I was able to get this to sort of work by doing the following:
{% for content in page.get_siblings %}
This worked to get the siblings as an experiment but of course the logic is no longer there to get the children. Below is my current code - I don't really know what I can do in the commented 3 lines of code to achieve my goal. I tried a few things but I haven't had any luck.
{% load static wagtailcore_tags menu_tags %}
<aside class="sidebar sidebar-boxed sidebar-dark">
<ul class="nav sidenav dropable sticky">
{% for content in page.get_children %}
<li class="{{ content.active_class }}">
<a href="{% pageurl content %}">{{ content.title }}</a>
#{% if content.has_children_in_menu %}
#{{ content.sub_menu.render_to_template }}
#{% endif %}
</li>
{% endfor %}
</ul>
</aside>
My expected result is that when I reach a last-child, the menu will display the siblings for the last-child as the menu rather than appear as blank.
I want a unique and consistent sidebar menu for each respective parent regardless of the child page that I navigate to.
Upvotes: 0
Views: 491
Reputation: 3098
The following uses only the Wagtail page hierarchy. It is limited to a two-level hierarchy.
{% load static wagtailcore_tags %}
<aside class="sidebar sidebar-boxed sidebar-dark">
<ul class="nav sidenav dropable sticky">
{% for item in page.get_children.live.in_menu %}
<li class="{{ item.active_class }}">
<a href="{% pageurl item %}">{{ item.title }}</a>
{% for subitem in item.get_children.live.in_menu %}
<li><a href="{% pageurl subitem %}{{ subitem.title }}</a></li>
{% empty %}
{% for sib in item.get_siblings.live.in_menu %}
<li><a href="{% pageurl sib %}{{ sib.title }}</a></li>
{% endfor %}
{% endfor %
</li>
{% endfor %}
</ul>
</aside>
Upvotes: 0