9

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.

5 Answers 5

42

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is a great solution but it won't work with namespaced URLs. In that case, you'd need to add a variable: {% with namespace=request.resolver_match.namespace url_name=request.resolver_match.url_name %}, and then the link markup should be like: <li class="{% if namespace == 'appname' and url_name == 'blog' %}active{% endif %}">Posts</li>.
2

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.

Comments

2

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> 

Comments

0

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> 

Comments

-1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.