Published on Dec. 10, 2023
Go homeHow to apply styling to the active view link in a Django template
It is useful on a navbar to indicate which link is the active page. The snippet below uses the request.resolver_match.url_name
to get the url name of the active view.
{% with request.resolver_match.url_name as url_name %}
<div class="flex flex-row gap-5 text-gray-800">
<a class="{% if url_name == 'dashboard' %}font-semibold{% endif %}" href="{% url 'core:dashboard' %}">Dashboard</a>
<a class="{% if url_name == 'diagnostics' %}font-semibold{% endif %}" href="{% url 'core:diagnostics' %}">Diagnostics</a>
</div>
{% endwith %}