Breadcrumbs

45 views
Skip to first unread message

Thomas Guettler

unread,
Jan 21, 2008, 7:06:22 AM1/21/08
to Django users
Hi,

I developed this method to create breadcrumbs.

What do you think about it?

Thomas

# Python
from urlparse import urljoin

# Django
from django import http
from django.core import urlresolvers
from django.core.urlresolvers import reverse
from django.conf import settings
from django.utils.http import urlquote

'''
Simple Breadcrumbs for Django:

The value of request.path gets examined and all views of the'upper' urls
need to have an attribute 'breadcrumbs'. They get added to the list of breadcrumbs. The attribute can be a
string or a method. If it is a method it needs to accept two arguments
(args and kwargs) which correspond to the arguments of the view.

Example: request.path == '/users/foo/settings/'

Views:

def settings(request, ...):
...
settings.breadcrumbs=u'Settings'

def user(request, username):
...
user.breadcrumbs=lambda args, kwargs: args[1]

def users(request):
...
users.breadcrumbs='Users'


Breadcrumbs:

Users>>foo>Settings

All except the last breadcrumb will be links the views.

Implemented with resolve(url)
'''
def get_breadcrumbs(request):
url=request.path
breadcrumbs=[]
urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
while url:
callback=None
try:
callback, callback_args, callback_kwargs = resolver.resolve(url)
except http.Http404, e:
pass
else:
bc=getattr(callback, 'breadcrumbs', None)
assert bc!=None, u'Callback %s.%s function breadcrumbs does not exist.' % (
callback.__module__, callback.__name__)
if not isinstance(bc, basestring):
bc=bc(callback_args, callback_kwargs)
if url!=request.path:
bc=u'<a href="%s">%s</a>' % (
urlquote(url), bc)
breadcrumbs.append(bc)

# Parent URL heraussuchen.
url=urljoin(url, '..')
if url=='/':
break
if not breadcrumbs:
return ''
breadcrumbs.append('')
breadcrumbs.reverse()
return u'<div class="breadcrumbs">%s</div>' % ('&gt;&gt;'.join(breadcrumbs))

def test_all_views():
u'''
Unittest: Check if all you views have a breadcrumbs()
attribute.

Django views are ignored.
'''
urlconf=settings.ROOT_URLCONF
resolver=urlresolvers.RegexURLResolver(r'^/', urlconf)
missing=[]
for function, patterns in resolver.reverse_dict.items():
if not function:
continue
sub_resolver=patterns[0]
if function.__module__.startswith('django'):
continue
name='%s.%s' % (function.__module__, function.__name__)
if not hasattr(function, 'breadcrumbs'):
missing.append(name)
bc=function.breadcrumbs
if isinstance(bc, basestring):
try:
unicode(bc)
except UnicodeError, exc:
missing.append('UnicodeError, %s: %s' % (name, exc))
missing.sort()
assert not missing, 'Missing breadcumbs function: %s' % (missing)

Reply all
Reply to author
Forward
0 new messages