26

Consider this basic menu:

<ul class="nav navbar-nav">
  <li class="active"><a href="{% url 'home' %}">Home</a></li>
  <li><a href="{% url 'about' %}">About</a></li>
</ul>

I'm trying to give the current page's link an active class, and I want to do this dynamically based on current url and the view's url. So that when a user visits the about page, that page now has the active class and the homepage does not.

I'd like to logic to work like this inside of the <li></li> tags:

{% if request.get_full_path = "{% url 'home' %}" %}class="active"{% endif %}
{% if request.get_full_path = "{% url 'about' %}" %}class="active"{% endif %}

but clearly I cant have two {% ... %} nested inside of each other.

Any ideas on how to get around nesting the two?

agconti
  • 16,911
  • 15
  • 76
  • 112

3 Answers3

50

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>
ArtOfWarfare
  • 19,191
  • 16
  • 128
  • 186
Alasdair
  • 278,338
  • 51
  • 534
  • 489
  • 2
    The additional advantage of this approach is that you need the `home_url` anyway when you're creating a link to it, so actually the only extra thing is the `if` on the `request.get_full_path`. Btw, for this, you'll need to add `request` to your template context variables, which you can put as a default context variable of course. – gitaarik Mar 11 '15 at 22:00
  • as of recent versions (certainly in 4.x) ```request``` seems to be automatically included in the template context by default – Martin CR Dec 26 '21 at 20:50
6

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>
hassanrazadev
  • 490
  • 6
  • 13
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'),
    # ...
]
Martin CR
  • 950
  • 9
  • 21
cizario
  • 3,582
  • 3
  • 12
  • 25