I have a base.html template that contains a list of links.
Example:
<div id="sidebar1">
<ul>
<li><a href="/" title="">Index</a></li>
<li><a href="/stuff/" title="" class="current">Stuff</a></li>
<li><a href="/about/" title="">About Me</a></li>
<li><a href="/contact/" title="">Contact Me</a></li>
</div>
Then I have in my views.py a definition for each of index.html, stuff.html, about.html and contact.html. Each of those templates simply derive from a base.html template and set their own respective titles and contents.
My question is about the above /stuff I have a class=”current”.
I’d like to make the current page that I’m on have that class attribute.
I could set a different variable in each view like current_page=”about” and then do a compare in the template with {% ifequal %} in each class element of each link , but that seems like duplicating work (because of the extra view variable).
Is there a better way? Maybe if there is a way to get the view function name that the template was filled from automatically I would not need to set the extra variable? Also it does seem like a lot of ifequals.
Here’s an elegant way to do this, which I copied from somewhere and I only wish I could remember where, so I could give them the credit. 😎
I assign an
idto each of my pages (or all the pages within a section) like this:And then an
idfor the corresponding links:And the in the CSS I set a rule like this:
So this works in a mostly declarative way to control the style of the link that the current page belongs in. You can see it in action here: http://entrian.com/source-search/
It’s a very clean and simple system once you’ve set it up, because:
switchstatements orif / else / elsestatementsI’m not using Django, but this system works anywhere. In your case, where you “set their own respective titles and contents” you also need to set the
body id, and there’s no other Django markup required.This idea extends easily to other situations as well, eg. “I want a download link in the sidebar on every page except the download pages themselves.” You can do that in CSS like this:
rather than having to put conditional template markup in the sidebar HTML.