Skip to content

Instantly share code, notes, and snippets.

@dryan
Created June 27, 2009 21:12
Show Gist options
  • Save dryan/137120 to your computer and use it in GitHub Desktop.
Save dryan/137120 to your computer and use it in GitHub Desktop.
Django middleware for adding selected and ancestor classes to nav links
class NavURLs(object):
def process_response(self, request, response):
if response.has_header('Content-Type') and response['Content-Type'].startswith('text/html') and not response.has_header('Location') and response.status_code == 200:
try:
nav_search = re.compile('.*nav.*')
content = BeautifulSoup(response.content)
navs = content.body(lambda tag: tag.name == 'nav' or (tag.has_key('id') and nav_search.match(tag['id']) != None) or (tag.has_key('class') and nav_search.match(tag['class']) != None))
for nav in navs:
for link in nav("a"):
if link['href'] == request.META['PATH_INFO']:
link['class'] = 'selected' if not link.has_key('class') else link['class'] + ' selected'
else:
path = re.compile('^' + link['href'] + '(.+)')
if path.match(request.META['PATH_INFO']):
link['class'] = 'ancestor' if not link.has_key('class') else link['class'] + ' ancestor'
response.content = content.renderContents()
except:
pass
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment