How to implement breadcrumbs in a Django template?

前端 未结 12 2081
無奈伤痛
無奈伤痛 2020-12-07 09:45

Some solutions provided on doing a Google search for \"Django breadcrumbs\" include using templates and block.super, basically just extending the base blocks and adding the

12条回答
  •  孤城傲影
    2020-12-07 10:18

    Something like this may work for your situation:

    Capture the entire URL in your view and make links from it. This will require modifying your urls.py, each view that needs to have breadcrumbs, and your templates.

    First you would capture the entire URL in your urls.py file

    original urls.py
    ...
    (r'^myapp/$', 'myView'),
    (r'^myapp/(?P.+)/$', 'myOtherView'),
    ...
    
    new urls.py
    ...
    (r'^(?Pmyapp/)$', 'myView'),
    (r'^(?Pmyapp/(?P.+)/)$', 'myOtherView'),
    ...
    

    Then in your view something like:

    views.py
    ...
    def myView(request, whole_url):
        # dissect the url
        slugs = whole_url.split('/')
        # for each 'directory' in the url create a piece of bread
        breadcrumbs = []
        url = '/'
        for slug in slugs:
            if slug != '':
                url = '%s%s/' % (url, slug)
                breadcrumb = { 'slug':slug, 'url':url }
                breadcrumbs.append(breadcrumb)
        
        objects = {
            'breadcrumbs': breadcrumbs,
        }
        return render_to_response('myTemplate.html', objects)
    ...
    

    Which should be pulled out into a function that gets imported into the views that need it

    Then in your template print out the breadcrumbs

    myTemplate.html
    ...
    
    ...
    

    One shortcoming of doing it this way is that as it stands you can only show the 'directory' part of the url as the link text. One fix for this off the top of my head (probably not a good one) would be to keep a dictionary in the file that defines the breadcrumb function.

    Anyways that's one way you could accomplish breadcrumbs, cheers :)

提交回复
热议问题