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.
Usage:
{% load make_breadcrumb_trail %}
{{ flatpage.url|crumbs:flatpage.title }}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | from django import template
from django.contrib.flatpages.models import FlatPage
register = template.Library()
def crumbs(url, title):
"Return breadcrumb trail leading to URL for this page"
t = title
s = ' > '
c = '<a href="/">Home</a>'
l = url.split('/')
for index, item in enumerate(l):
if item == '':
del l[index]
n = len(l)
if n > 1:
l[0] = '/' + l[0] + '/'
for i in range(1, n-1):
l[i] = l[i-1] + l[i] + '/'
for index2, item2 in enumerate(l):
q = FlatPage.objects.filter(url=l[index2])
if q:
qa = '<a href="%s">%s</a>' % (q[0].url, q[0].title)
c = c + s + qa
c = c + s + t
return c
register.filter('crumbs', crumbs)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
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.
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.
Thanks!
#
Please login first before commenting.