Hello.
I am using django-treebeard to build a tree-like navbar. Some top level elements of the navbar will have nested elements.
I followed advices from this post to get a working example of the navbar:
Django template nested loop
# models.py
class BaseNav(MP_Node):
name = models.CharField(max_length=100)
url = models.CharField(max_length=100)
position = models.PositiveIntegerField(default=1)
node_order_by = ['position']
class Meta:
abstract = True
def __str__(self):
return self.name
class HeaderNav(BaseNav):
class Meta:
verbose_name='Header Navbar'
verbose_name_plural='Header Navbar'
An inclusion tag of navbar:
# app/templatetags/navigation_tags.py
@register.inclusion_tag('app/blocks/header-navbar.html', takes_context=True)
def show_header_navbar(context):
root = HeaderNav.get_first_root_node()
return {'root': root}
Templates:
# header-navbar.html (parent template)
<ul class="navbar-nav">
{% include 'app/blocks/header-navbar-items.html' with node=root only %}
</ul>
# header-navbar-items.html (child template)
{% if node.is_leaf %}
<li class="nav-item px-4">
<a class="nav-link" href="{{ node.url }}">{{ node.name }}</a>
</li>
{% else %}
<li class="nav-item dropdown px-4">
<a href="#" class="nav-link dropdown-toggle" id="navbarDarkDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false">
{{ node.name }}
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
{% for child in node.get_children %}
{% include 'app/blocks/header-navbar-items.html' with node=child only %}
{% endfor %}
</ul>
</li>
{% endif %}
And the structure of the navbar from admin:
Everithing worked well and I got this as a result:
The problem is: I don’t want the root node to be shown on the page. What I really need is root’s children and descendants (shown below).
Any help on this would be appreciated.