Django – Highlight Navigation based on current page?

Assuming you use render_to_response with RequestContext or use the render method or class-based views of Django 1.3, you’ll have the request object available in your template. From there, it’s a simple matter of just accessing the current path and comparing it with expected values:

<a href="https://stackoverflow.com/some/path/to/be/highlighted/"{% if request.path == "https://stackoverflow.com/some/path/to/be/highlighted/" %} class="active"{% endif %}>Some Link</a>

In Django 1.3, I like to save redundancy and use the as operator for the URL lookup:

{% url 'some_urlpattern_name' as url %}
<a href="https://stackoverflow.com/questions/7665514/{{ url }}"{% if request.path == url %} class="active"{% endif %}>Some Link</a>

Repeat as necessary for each link.

Leave a Comment