Login

URL based breadcrumbs

Author:
phlex
Posted:
March 22, 2008
Language:
Python
Version:
.96
Score:
3 (after 3 ratings)

This is a simple URL based breadcrumb filter I'm using on a site I'm currently building. To use it, just throw the code into template-tag file, and simply pass the current url in a page template like so

{{ request.get_full_path|breadcrumbs }}

As an example of how to style it, wrap it in a unordered list with an id of breadcrumb, and then in your styles use #breadcrumb li { display: inline; }.

On a contact form for a site user, this will produce something along the lines of

you are here : home » users » username » contact form

Hopefully someone may find it useful.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
@register.filter
def breadcrumbs(url):
    home = ['<li>you are here : <a href="/" title="Breadcrumb link to the homepage.">home</a> &raquo;</li>',]
    links = url.strip('/').split('/')
    bread = []
    total = len(links)-1
    for i, link in enumerate(links):
        if not link == '':
            bread.append(link)
            this_url = "/".join(bread)
            sub_link = re.sub('-', ' ', link)
            if not i == total:
                tlink = '<li><a href="/%s/" title="Breadcrumb link to %s">%s</a> &raquo;</li>' % (this_url, sub_link, sub_link)
            else:
                tlink = '<li>%s</li>' % sub_link
            home.append(tlink)
    bcrumb = "".join(home)
    return mark_safe(bcrumb)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

macmichael01 (on December 5, 2008):

You should at this in at line no. 7

if len(link) > 0 and link[0] == '?': break

so you don't append GET variables as a breadcrumb link.

#

macmichael01 (on December 5, 2008):

opps one other change, line no. 12:

if not i == total and not links[i+1][0] == '?':

That way it does not make a link out of the current location if there are GET variables in the url.

#

Please login first before commenting.