Menu Close

How to highlight links in Python Django templates?

Sometimes, we want to highlight links in Python Django templates

In this article, we’ll look at how to highlight links in Python Django templates

How to highlight links in Python Django templates?

To highlight links in Python Django templates, we can create a tag.

For instance, we write

@register.simple_tag
def active(request, pattern):
    import re
    if re.search(pattern, request.path):
        return 'active'
    return ''

to create the active tag that returns 'active' if the current URL patches the path pattern for the link.

We use the @register.simple_tag tag to register the template tag.

Then in urls.py, we add some routes by writing

urlpatterns += patterns('',
    (r'/$', view_home_method, 'home_url_name'),
    (r'/services/$', view_services_method, 'services_url_name'),
    (r'/contact/$', view_contact_method, 'contact_url_name'),
)

And then in a template, we write

{% load tags %}

{% url 'home_url_name' as home %}
{% url 'services_url_name' as services %}
{% url 'contact_url_name' as contact %}

<div id="navigation">
    <a class="{% active request home %}" href="{{ home }}">Home</a>
    <a class="{% active request services %}" href="{{ services }}">Services</a>
    <a class="{% active request contact %}" href="{{ contact }}">Contact</a>
</div>

to use the active tag to set the class attribute to active if the link URL matches the current URL.

Conclusion

To highlight links in Python Django templates, we can create a tag.

Posted in Python, Python Answers