51๐
I usually use template inheritance in my navigation, in a similar way to the answer alecxe linked to. However, it is possible to compare the use the current URL in an if tag, as you are trying to do.
The url
tag allows you to save the result to a variable. You can then use that variable in your if tag.
{% url 'home' as home_url %}
<a href="{{ home_url }}" {% if request.get_full_path == home_url %}class="active"{% endif %}>Home</a>
9๐
Very old thread! My answer might help future readers.
I did that this way (just compare request URL name with your pathname)
<a class="nav-link {% if request.resolver_match.url_name == 'index' %}active{% endif %}" href="#">Home</a>
- [Django]-Django Admin โ Disable the 'Add' action for a specific model
- [Django]-Renaming an app with Django and South
- [Django]-Django Framework โ Is there a shutdown event that can be subscribed to?
0๐
if your app has a namespace
(let say blog
) then:
<li class="nav-item">
<a
class="nav-link{% if request.resolver_match.namespace == 'blog' and request.resolver_match.url_name == 'post_list' %} active{% endif %}"
href="{% url 'blog:post_list' %}">
Blog
</a>
</li>
remember to define app_name
in blog/urls.py
:
app_name = 'blog'
urlpatterns = [
path('', views.post_list, name='post_list'),
# ...
]
- [Django]-Django form.as_p DateField not showing input type as date
- [Django]-How can I avoid "Using selector: EpollSelector" log message in Django?
- [Django]-How can I get a decimal field to show more decimal places in a template?
0๐
The templatetags are very useful for this kind of need. Moreover, the templatetag can access the context and the request. Use the following as an idea to tailor up based on your needs.
# yourapp/templatetags/utils.py
from django import template
from django.urls import reverse
register = template.Library()
@register.simple_tag(takes_context=True)
def get_active_class(context, url_to_check: str) -> str:
request = context['request']
if request.get_full_path() == reverse(url_to_check):
# this could be in the settings or in the app config
return "is-active"
return ""
In your sidebar you can now create a link easily
# your sidebar.html somewhere in your code
{% load utils %}
<ul class="menu-list">
<li>
<a
href="{% url 'home' %}"
class="{% get_active_class 'home' %}">Home
</a>
</li>
<li>
<a
href="{% url 'settings' %}"
class="{% get_active_class 'settings' %}">Home
</a>
</li>
</ul>
- [Django]-How to setup SSL on a local django server to test a facebook app?
- [Django]-How to change empty_label for modelForm choice field?
- [Django]-How to see details of Django errors with Gunicorn?