Setting active navbar link in Django template

Here is probably the best way to set the active navbar link in Django template. Note, this needs no jQuery/ javascript.

Step 1

Create named urls:

Step 2

Create a Navbar template. I keep it stored in a file called navbar.html inside “templates/base” folder. This “templates” folder is at same level as manage.py
I am using bootstrap 4 navbar component.

In bootstrap 4, “active” class is put on the currently active link. This is the best way to do it using Django templates:
{% if request.path == ecomproduct_url %} active {%endif%}
This will highlight “Products” in navbar. Note, this way also needs you to first create a variable for the named url like so {% url 'ecom_product:list' as ecomproduct_url %}

Step 3

Include the navbar like so:




No Comments


You can leave the first : )



Leave a Reply

Your email address will not be published. Required fields are marked *