How do i show an active link in a django navigation bar dropdown list?

Viewed 6862

I have a navbar menu with a list of links which i want to show the active link when the user is on the page, so far i have managed to do this with links that dont have dropdowns like this.

enter image description here

But I cannot seem to get it right with the dropdown links in such a way that if the user is on a page on the dropdown link the parent link on the navbar gets highlighted.like shown below

enter image description here

Any help would be greatly appreciated.

4 Answers

If you define your URLs with names like this:

url('', 'home_view', name='home'),
url('posts/', 'posts_view', name='blog'),
url('contact/', 'contact_view', name='contact'),

You can use these names in the template to make the if statements work:

{% with request.resolver_match.url_name as url_name %}
    <ul id="menu">
        <li class="{% if url_name == 'home' %}active{% endif %}">Home</li>
        <li class="{% if url_name == 'blog' %}active{% endif %}">Posts</li>
        <li class="{% if url_name == 'contact' %}active{% endif %}">Contact</li>
    </ul>
{% endwith %}

This saves you from problems with duplication in url paths.

You can do this by passing a variable in context dictionary views.

Example:

context['faculties']=True

and then in html

{% if faculties %}active{% endif %} 

For every view function you can set a variable to which you want to make active.

There are two ways: either manage your CSS to highlight the parent item if any of its children are "active" or (at the expense of some maintenance overhead and loss of DRY) test for membership in the template:

<li class="dropdown {% if url_name in "neo_app:business,neo_app:IT,neo_app:hospitality" %}
                       active
                    {% endif %}>Faculties</li>

You can do this all on the front end very easily without passing anything from the backend based on the URL.

If your url for example is "/faculties", you can do:

{% if '/faculties' in url %} active {% endif %}
Related