Custom Search

Tuesday, April 20, 2010

django template tag for highlight nav item

django template tag for highlight nav item django template tag for highlight selected nav item

-------------------------- in template

<div id="menu">
<ul id="nav-menu">
<li class="{% active_page request.path dashboard %}"> <a href="{% url dashboard %}">Dashboard</a> </li>
<li class="{% active_page request.path dashboard_todo_list %}"> <a href="{% url dashboard_todo_list %}">To-Dos</a> </li>
<li class="{% active_page request.path dashboard_milestone_list %}"> <a href="{% url dashboard_milestone_list %}">Milestones</a> </li>
<li class="{% active_page request.path ticket_list %} last"> <a href="{% url ticket_list %}">Tickets</a> </li>
</ul>
</div>

-------------------------- in templatetags/tags.py

class ActivePageNode(template.Node):
def __init__(self ,tag_name, path, url):
self.path = path
self.url = url
self.tag_name = tag_name

def render(self, context):
self.path = template.resolve_variable(self.path, context)
print "path -->", self.path
print "url -->", reverse(self.url)
if self.path == reverse(self.url):
print "equal"
return 'current'


@register.tag
def active_page(parser, token):
try:
tag_name, path, url = token.split_contents()
print "tag name:", tag_name
print "path:", path
print "url:", url
except ValueError:
raise template.TemplateSyntaxError
return ActivePageNode(tag_name, path, url)


--------------------------

output
---------
tag name: active_page
path: request.path
url: dashboard

tag name: active_page
path: request.path
url: dashboard_todo_list

tag name: active_page
path: request.path
url: dashboard_milestone_list

tag name: active_page
path: request.path
url: ticket_list

path --> /siren/dashboard/milestones/
url --> /siren/dashboard/

path --> /siren/dashboard/milestones/
url --> /siren/dashboard/todolists/

path --> /siren/dashboard/milestones/
url --> /siren/dashboard/milestones/
equal

path --> /siren/dashboard/milestones/
url --> /siren/dashboard/tickets

--------------------------------

No comments:

Post a Comment