Skip to content

Instantly share code, notes, and snippets.

@delneg
Created April 12, 2017 18:00
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save delneg/b6d625708ae1a75fd5f036a5fe6f6a62 to your computer and use it in GitHub Desktop.
Save delneg/b6d625708ae1a75fd5f036a5fe6f6a62 to your computer and use it in GitHub Desktop.
Django 'active' for navbar
# In this example I make difference for 3 urls, this can be messy if you have an URL that is like /posts/whatever/contacts because there is 2 places that will return True (2nd and 3rd li)
# So here is the better option for handling this:
{% with request.resolver_match.url_name as url_name %}
<ul id="menu">
<li class="{% if url_name == 'home' %}active{% endif %}">Home</li>
<li class="{% if url_name == 'blog' %}active{% endif %}">Posts</li>
<li class="{% if url_name == 'contact' %}active{% endif %}">Contact</li>
</ul>
{% endwith %}
# Now we don't have problem with duplications in our url paths. That will work, assuming that you have wrote your url patterns with names like this:
url(r'^$', 'home_view', name=u'home'),
url(r'^posts/$', 'posts_view', name=u'blog'),
url(r'^contact/$', 'contact_view', name=u'contact'),
@DimaZimin
Copy link

Привет, я только начинаю изучать Джанго и это то, что я искал. Спасибо большое тебе :)

@str2hex
Copy link

str2hex commented Dec 28, 2022

Работает
Спасибо.

@khawar11
Copy link

thank you for this.

@Mohammadparsa1384
Copy link

thank you ❤

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment