Accessing dictionaries inside lists with Django templates

Today while working on the new SVO i ran into an issue with the coding of breadcrumbs. I wanted to pull the breadcrumb code out of each page template and put it into the header template.

This is what i had originally in each template:

<p id="breadcrumbs">
    <a href="/">Home</a><span class="bc_sep">></span>
    <a href="{% url videos %}">Videos</a><span class="bc_sep">></span>
    <a href="{% url company video.company.id video.company.name|slugify %}">{{ video.company.name }}</a><span class="bc_sep">></span>
    <strong>{{ video.name }}</strong>
</p>

This quickly became annoying, repeating this code in every page’s template. I decided to create a list of dictionaries inside each view to represent the breadcrumbs:

breadcrumbs = []
breadcrumbs.append( { 'home':reverse( 'home' ) } )
breadcrumbs.append( { 'skaters':reverse( 'skaters' ) } )
breadcrumbs.append( { index:'' } )
return render_to_response('index.html', {...'breadcrumbs':breadcrumbs})

Then in my template i loop the list and dictionary:

<p id="breadcrumbs">
{% for breadcrumb in breadcrumbs %} #this loops the list
	{% for text, link in breadcrumb.items %} #this extracts the dictionary inside each list
		{% if link %}
			<a href="{{ link }}">{{ text|capfirst }}</a><span class="bc_sep">></span>
		{% else %}
			<strong>{{ text|capfirst }}</strong>
		{% endif %}
	{% endfor %}
{% endfor %}
</p>

Add a response

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">