Breadcrumbs for flatpages

Custom template filter to generate a breadcrumb trail for a flatpage. Say you have a series of flatpages with URLs like /trunk/branch/leaf/ etc. This filter looks at the URL of a given flatpage, figures out which of the leftwards text chunks correspond to other flatpages, and generates a string of anchored HTML.

fromdjangoimporttemplatefromdjango.contrib.flatpages.modelsimportFlatPageregister=template.Library()defcrumbs(url,title):"Return breadcrumb trail leading to URL for this page"t=titles='&nbsp;&nbsp;&gt;&nbsp;&nbsp;'c='<a href="/">Home</a>'l=url.split('/')forindex,iteminenumerate(l):ifitem=='':dell[index]n=len(l)ifn>1:l[0]='/'+l[0]+'/'foriinrange(1,n-1):l[i]=l[i-1]+l[i]+'/'forindex2,item2inenumerate(l):q=FlatPage.objects.filter(url=l[index2])ifq:qa='<a href="%s">%s</a>'%(q[0].url,q[0].title)c=c+s+qac=c+s+treturncregister.filter('crumbs',crumbs)

More like this

Comments

<p>Great Snippet that works perfectly. Just a heads-up for anyone else wanting to use this: Don't forget that the app in which this template is installed must be included in INSTALLED_APPS in settings.py. </p>
<p>For example, I have a utils app that contains code used project-wide. I installed this snippet into myproject.utils.templatetags.make_breadcrumb_trail but the {% load make_breadcrumb_trail %} failed until I added 'myproject.utils' to my INSTALLED_APPS.</p>
<p>Thanks!</p>