Skip to content

Instantly share code, notes, and snippets.

@stephenemslie
Created February 3, 2011 12:35
Show Gist options
  • Save stephenemslie/809420 to your computer and use it in GitHub Desktop.
Save stephenemslie/809420 to your computer and use it in GitHub Desktop.
Very simple but useful Django context processor to generate a ResolverMatch object from request.path and add this to the context. Handy in checking for active urls or namespaces.
"""
resolved_pattern Django context processor: insert the current url's ResolverMatch object into context.
Example use: Set class=active to a menu item, based on the namespace of the currently matched url.
<li {% if resolved.namespace == "home" %}class="active"{% endif %}> home </li>
or more specifically:
<li {% if resolved.view_name == "contact" %}class="active"{% endif %}> contact </li>
See http://docs.djangoproject.com/en/dev/topics/http/urls/#django.conf.urls.defaults.ResolverMatch
"""
from django.core.urlresolvers import resolve
def resolvermatch(request):
"""Add the name of the currently resolved pattern to the RequestContext"""
match = resolve(request.path)
if match:
return {'resolved': match}
else:
return {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment