Hello,
I am writing a python website built on the back of the django framework, I am looking for a way to highlight the current link the user is on depening on what the URL, I thought doing some thing like this would work.
What I have done is create a new application called nav
and built some templatetags, like so,
from django import template
register = template.Library()
URL_PATTERNS = {
'home': (r'^/$',),
}
@register.tag
def nav_selection(parser, token):
try:
tag_name, nav_item = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0]
if not (nav_item[0] == nav_item[-1] and nav_item[0] in ('"', "'")):
raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
return NavSelectionNode(nav_item[1:-1])
class NavSelectionNode(template.Node):
def __init__(self, nav_item):
self.nav_item = nav_item
def render(self, context):
if not 'request' in context:
return ""
import re
try:
regs = URL_PATTERNS[self.nav_item]
except KeyError:
return ''
for reg in regs:
if re.match(reg, context['request'].get_full_path()):
return "active"
return ''
In my template I do this
<ul id="navigation">{% load nav %}
<li><a href="{% url views.home %}" class='{% nav_selection "home" %}'>home</a></li>
<li><a href="{% url views.about %}" class='{% nav_selection "about" %}'>about neal & wolf</a></li>
<li><a href="{% url shop.views.home %}" class='{% nav_selection "shop" %}'>our products</a></li>
<li><a href="{% url shop.views.home %}" class='{% nav_selection "shop" %}'>shop</a></li>
<li><a href="{% url views.look %}" class='{% nav_selection "look" %}'>get the look</a></li>
<li><a href="{% url news.views.index %}" class='{% nav_selection "news" %}'>news</a></li>
<li><a href="{% url contact.views.contact %}" class='{% nav_selection "contact" %}'>contact us</a></li>
<li><a href="{% url store_locator.views.index %}" class='{% nav_selection "finder" %}'>salon finder</a></li>
<li><a href="{% url professional.views.index %}" class='{% nav_selection "contact" %}'>neal & wolf professional</a></li>
</ul>
yet the markup I get out in firebug is this in this example I am browsing the index page
<a class="" href="/home/">
So something is obviously failing but I cannot see where, can anyone help me please?