gathagu
gathagu

Reputation: 351

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

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.

Upvotes: 9

Views: 12506

Answers (5)

Rok Sprogar
Rok Sprogar

Reputation: 2401

For namespaced urls, I do it like this:

<a href="{% url 'frontend:index' %}"{% if request.resolver_match.app_name|add:":"|add:request.resolver_match.url_name == 'frontend:index' %} class="active"{% endif %}>Home</a>

Upvotes: 0

xnx
xnx

Reputation: 25548

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>

Upvotes: 2

Siddharth Pant
Siddharth Pant

Reputation: 790

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.

Upvotes: 40

csling
csling

Reputation: 328

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 %}

Upvotes: -1

Astik Anand
Astik Anand

Reputation: 13057

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.

Upvotes: 2

Related Questions