Bootstrap navigation active nav link tip for Django template

Almost all the application on the web has navigation bar or menu bar. So that user can navigate within the application easily. Each time you click on the link, active link which you are differentiated with some more styles.

If you your Django application has one or two pages, you can hard code them. But this is not always the case. So you might have base template and different HTML files for header, navigation, menu bar, content and footer.

Server side rendering is that the html you see in the browser is generated by the server based on request and sent to your client browser.

So It makes little harder to differentiate active link for server side rendering pages as you need to remember with the request or have to manage in your backend code. Here is a little tip how I managed it on my file sharing service.

What you need to know

For this task, I used to bellow built-ins and context processing from django template.

  1. URL Path from request context processing
  2. If built-in
  3. with built-in

Template Code


Based on the path you can enable active CSS class.

Path variable

You can access the path variable in Django request object. But to access request object in Django template, you need to add request context processor in the template setting. It is added by default.

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

With built-in

With built-in is used in step 1 for not repeating request.path for navigation links.

If built-in

If built-in to place CSS class for active link based on path as step 2.

Example code

{% with path=request.path %}
<nav class="nav nav-header justify-content-center mt-4">
<a class="nav-link {% if path == '/' %}active{% endif %}" href="/">HOME</a>
<a class="nav-link {% if path == '/contact' %}active{% endif %}" href="{% url 'contact' %}">CONTACT US</a>
</nav>
{% endwith %}

With this you be able to get the same effect as this example.


Happy reading. Please comment if you are stuck or you have any questions.

Comments
We'll never share your email with anyone else.