connexion20000
connexion20000

Reputation: 335

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:

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

Upvotes: 4

Views: 2542

Answers (2)

amureki
amureki

Reputation: 772

@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'),

Upvotes: 21

AlvaroAV
AlvaroAV

Reputation: 10563

To show active tabs in menus & submenus I use request.path in the Templates and one class called active.

When you do

{{request.path}}

in a template it returns the url where you are(something like /posts/1234). So in your HTML you can do something like:

<ul id="menu">
    <li class="{% if request.path == '/' %}active{% endif %}">Home</li>
    <li class="{% if 'posts' in request.path %}active{% endif %}">Posts</li>
    <li class="{% if 'contact' in request.path %}active{% endif %}">Contact</li>
</ul>

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)

But If you have very different urls this could be one of the easiest ways to do what you're trying to do

Upvotes: 4

Related Questions