I want to highlight the current page in the navigation menu. Obviously I need to give the menu links a class like 'active' when you are on their page. This is a classic problem and I've seen many solutions proposed. My problem is I hate all of them and consider none of them to be very DRY. For example:
@register.simple_tag
def active(request, pattern):
import re
if re.search(pattern, request.path):
return 'active'
return ''
----
{% load tags %}
<div id="navigation">
<a class="{% active request "^/about/" %}" href="/about/">About</a>
<a class="{% active request "^/contact/" %}" href="/contact/">Contact</a>
<a class="{% active request "^/services/" %}" href="/services/">Services</a>
</div>
The tag takes your current request and a url expression and returns 'active' if you're currently on this page. Alternatively this can be done with named views rather than urls but the principle is the same.
My main issue with this is that my navigation will be called on 99% of my views and yet, in order to get the current request variable I still have parse a RequestContext to the template with something like this:
def contact(request):
# snip ...
return render_to_response(
'contact.html',
{ 'myvar' : myvar },
context_instance=RequestContext(request))
Why do I need to add this context_instance line to every single one of my views when probably all but one of them needs the request variable in order to get the current url/view to highlight the active link? This seems awfully wet, especially for a feature that must be in the great majority of django sites. I want the request to be included by default and be able to optionally suppress it. I can't find a way to do this in middleware as I can't intercept the template before its rendered after the view has returned it.
Any suggestions?