tags:

views:

436

answers:

3

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?

+1  A: 

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.

Brian R. Bondy
Sounds interesting... I'm sure it will work, but I'll await further answers to see if something else suits my taste better! :) Thanks.
Deniz Dogan
A: 

You can pass request.path to your template

from django.shortcuts import render_to_response
from django.template import RequestContext
return render_to_response('templ.html', {'page':request.path}, context_instance=RequestContext(request))

then use an ugly if template tag to add a CSS class to your menu item

jujule
A: 

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 %}
SmileyChris