Getting Started¶
We’ll add a navigation bar to a Django project — define the structure in Python, write a template, and render it.
This assumes you’ve already installed the package and have a Django project with at least one view and template.
Create the template¶
Now we need the main_nav.html that our Nav points to. The template receives the items we defined above — each has a title, url, and groups have nested items. Create it in your templates directory:
<!-- main_nav.html -->
<nav>
<ul>
{% for item in items %}
<li>
<a href="{{ item.url }}">{{ item.title }}</a>
{% if item.items %}
<ul>
{% for subitem in item.items %}
<li><a href="{{ subitem.url }}">{{ subitem.title }}</a></li>
{% endfor %}
</ul>
{% endif %}
</li>
{% endfor %}
</ul>
</nav>
Highlight the active page¶
Each item also has an active property that’s True when its URL matches the current request. Let’s use it to highlight the current page:
<!-- main_nav.html -->
<nav>
<ul>
{% for item in items %}
<li>
<a href="{{ item.url }}"{% if item.active %} class="active"{% endif %}>
{{ item.title }}
</a>
{% if item.items %}
<ul>
{% for subitem in item.items %}
<li>
<a href="{{ subitem.url }}"{% if subitem.active %} class="active"{% endif %}>
{{ subitem.title }}
</a>
</li>
{% endfor %}
</ul>
{% endif %}
</li>
{% endfor %}
</ul>
</nav>
Reload the page — the link for the current page will now have the active class. You can style it with CSS to make it stand out.
Next steps¶
That’s it — a navigation defined in Python, rendered in a template. From here you can:
Control which items are visible based on the user’s permissions
Pass extra data to templates for icons, badges, or other custom rendering
Use Jinja2 templates instead of Django templates
Let items render themselves for less template boilerplate
See the reference for full details on all attributes and behaviors.