Django tip: active-link template tag

Here's a simple template tag that allows easily mark current links with a custom class. I believe it is necessary in each Django-powered project (except for those DRF-ed).

from django import template  
from django.http import HttpRequest

register = template.Library()


@register.simple_tag(takes_context=True)
def active_path(context, url_name, classname='active'):
"""
Check if the current resolved path name equals the `url_name` param
and return the `classname` param value if true. """

request: HttpRequest = context['request']
resolved_name = request.resolver_match.url_name
if resolved_name == url_name:
return classname
return ''

How to install the template tag?

  1. In one of your Django project apps (I prefer to have an app named project_name.core for such cases) create a package named templatetags
  2. Inside the newly created package, create a file named navigation.py
  3. Put the above contents to the created file

Now you can use it in your template:

  1. First, inform the template engine that you'll be using the navigation template tags package
  2. Use the tag inside a class attribute, as presented below
<a href="{% url 'item-list' %}" class="{% active_path 'item-list' 'active-link' %}">Item list</a>

Now, when a user enters the page that matches the item-list path name (declared in urls) then the <a> tag will get a class named active-link.

Voila!