Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Figure out which item in a menu that has been selected

Tags:

django

menu

I'm sure I've seen this question on Stack Overflow before, but I couldn't find it by my life, so here goes nothing.

I have a normal Django menu which uses the {% url %} tag and static names for the menu items. Now I want to have a different style for the menu item which has been selected. But the menu is being rendered in the base template, so how do I figure out which menu item it is?

like image 343
Deniz Dogan Avatar asked Dec 23 '22 09:12

Deniz Dogan


2 Answers

You could surely do this with some ugly template code, but a better more globally known way is to use a CSS selector. This lets CSS do all of the work automatically for you.

Here's how it works:

You simply put an id in your body depending on which page you are on. Then in css you do something like this:

#section-aboutme #nav-aboutme,
#section-contact #nav-contact
/* ... put one of these per body/menu item ... */
{
    font-color: red;
}

You put the nav-aboutme, and nav-contact ids on each of your menu items.

The style will automatically be selected by CSS depending on which body id they are inside of.

like image 125
Brian R. Bondy Avatar answered May 08 '23 15:05

Brian R. Bondy


I normally do it the way Brian suggested, but to accommodate for a template which a designer gave me which used the more common class="selected" method, I wrote a {% nav %} template tag.

Your HTML navigation template will look something like:

{% block nav %}
<ul class="nav">
    <li{% if nav.home %} class="selected"{% endif %}><a href="/">Home</a></li>
    <li{% if nav.about %} class="selected"{% endif %}><a href="/about/">About</a></li>
</ul>
{% endblock %}

To set the navigation in a child template, do:

{% include "base.html" %}
{% load nav %}

{% block nav %}
{% nav "about" %}
{{ block.super }}
{% endblock %}
like image 31
SmileyChris Avatar answered May 08 '23 16:05

SmileyChris