Dec 09, 2016

Snippet: Breadcrumbs

Pablo Iglesias


Snippets: Breadcrumbs

The use of breadcrumbs in many of the apps that we develop and maintain is very common. It’s because of that we thought about making it easier. After reviewing some libraries we decided to create a simple snippet with the idea of saving time and being able to handle all the breadcrumbs from the same site in a global variable.

The first step was to decide to use a  context processor,  is a list of dotted Python paths to callables that are used to populate the context when a template is rendered with a request, because it’s going to execute before the template rendering, then we must add it in We tried this snippet in django 1.8+ and using i18n in the texts :

'context_processors': [

In the following snippet we can see how we look for the name of the view in a dictionary and if it exists, we return it.

from django.core.urlresolvers import resolve
from django.conf.settings import breadcrumbs_views

def breadcrumbs(request):
   Context processor for include general breadcrumb in the mains views
   :return: dictionary with the breadcrumb for each view
   view_name = resolve(request.path_info).url_name
   if view_name in breadcrumbs_views:
       return {'breadcrumbs': breadcrumbs_views[view_name]}
   return {}

To know what to display, we read a variable that is in called breadcrumbs_views. It’s a dictionary containing the name of the view as a key and a list of tuples (name of view, text to show) as value. In the following example we can see how the Home views show “Start” and the contact view it’s going to show “Start” and “Contact”.

home = (_('Start'), 'home')
breadcrumbs_views = {
                     'home': [home],
                     'index': [(_('Landing'), 'index')],
                     'contact': [home, (_('Contact'), 'contact')],

Unlike some libs, we have decided to have all this information in a single variable, since this allows us to see the relationship between all views from a single file, otherwise we would have to go view by view to see what breadcrumb it’s going to show.

To finish, we have created a block for the templates and added it in our base.html:

{% block breadcrumbs %}
   {% include 'breadcrumbs.html'%}
{% endblock breadcrumbs %}

<div class="breadcrumbs">
    {% for crumb in breadcrumbs %}
        {% if not forloop.last %}
            <a class="breadcrumb "href="{% url crumb.1 %}"> {{ crumb.0 }} </a>
        {% else %}
            <a class="breadcrumb current">{{ crumb.0 }}</a>
        {% endif %}
    {% endfor %}

Now you can see how our breadcrumbs works:


From BeDjango we like to share our knowledge and the tricks we’re using. We are aware this snippet can be improved and extended with more options, so give it a try and give us some feedback. We've created a gist with the code to make the work easier.


Leave a comment