Metronic - Django - Set menu item to active
Hi,
I'm trying to simply set the menu item to active after clicking.
I'm assuming that I need to use the "KTTheme.addHtmlClass" method in the view file, but I have no idea how to add the "active" class to menu item.
Help would be greatly appreciated
Replies (3)
Hello,
The function KTTheme.addHtmlClass
might not be suitable for your specific case.
To provide an example, if you were to use the KTTheme.addHtmlClass
function to add a class to the body
element like this:
KTTheme.addHtmlClass('body', 'app-default')
the added class will be printed when you use the printHtmlClasses
function in the HTML code like this:
<body {% printHtmlClasses 'body' %}>
However, using the KTTheme.addHtmlClass
function in this way does not allow you to differentiate which menu to set as active. This means that if you need to set a specific menu as active, you will need to use a different method.
You can use the request object to get the current URL and then use conditional statements to set the active class to the menu.
Here's an example:
<li class="menu-item {% if request.path == '/' %}active{% endif %}">
<a class="menu-link" href="{% url 'home' %}">Home</a>
</li>
<li class="menu-item {% if request.path == '/about/' %}active{% endif %}">
<a class="menu-link" href="{% url 'about' %}">About Us</a>
</li>
<li class="menu-item {% if request.path == '/contact/' %}active{% endif %}">
<a class="menu-link" href="{% url 'contact' %}">Contact Us</a>
</li>
In the above code, we're using the request.path
attribute to get the current URL or route and comparing it with the URL or route of each menu item using the Django template if statement. If the current URL or route matches the URL or route of a menu item, then we're adding the active class to that menu item.
Thanks
Thank you so much! This is exactly what I was looking for
You're welcome! I'm glad I could be of help. If you have any more questions or concerns in the future, don't hesitate to ask.