pythondjangoweb

How to add active class in django?


I have a sidebar where there are links to some pages that have active class if url matches to name of link. But there are also links to pages that I add with for loop in my template. I need to somehow add active class when they are opened. I use id to link them.

template:

{% for branch in branches %}
    <li>
        <a href="{% url 'manager-branch-workers' branch.id %}">{{branch.name}}</a>
    </li>
{% endfor %}

urls.py:

urlpatterns = [
    ...
    path('workers/<int:pk>/', views.BranchWorkerList, name='manager-branch-workers')
]

Can I compare id and url path?


Solution

  • You've got two options available to you:

    Option 1:

    Pass the value of pk as part of your template context and access that value in the template:

    class BranchWorkerView(View):
        def get(self, request, pk, *args, **kwargs):
            ...
            context = {
                "pk": pk,
            }
            return render(request, "template_name.html", context)
    
    {% for branch in branches %}
        <li>
            <a
                href="{% url 'manager-branch-workers' branch.id %}"
                {% if pk == branch.id and request.resolver_match.url_name == "manager-branch-workers" %}
                class="active"
                {% endif %}>
                {{branch.name}}
            </a>
        </li>
    {% endfor %}
    

    Option 2:

    Access the pk value directly from the path in your template:

    {% for branch in branches %}
        <li>
            <a
                href="{% url 'manager-branch-workers' branch.id %}"
                {% if request.resolver_match.kwargs.pk == branch.id and request.resolver_match.url_name == "manager-branch-workers" %}
                class="active"
                {% endif %}>
                {{branch.name}}
            </a>
        </li>
    {% endfor %}
    

    In both cases, you'll need to access some data from the request object by making use of the resolver_match attribute within the template itself. See the documentation here.