Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Styling current navigation menu item in Django

I would like to style currently active submenu item in Django. I am wondering how should I do it? I can think of 2 ways:

  • Django Side: where I compare current address with link and then I add inside Django template
  • jQuery side: where Django template knows nothing about active menu item nad I do highlights using jQuery

I am more prone to do it jQuery way, but is my way of thinking good? Is this solution not recommended somehow?

like image 869
connexion20000 Avatar asked Nov 28 '22 01:11

connexion20000


1 Answers

@Liarez in his answer wrote:

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'),
like image 114
amureki Avatar answered Dec 04 '22 05:12

amureki