Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of tuples in django template

I have a list of labels and a list of values in my views, where the nth element in the first list corresponds to the nth element of the second list , I want to display them in order in my template, in a list or a tab , for example :

- label1 : text1 
- label2 : text2 ..

To do so, I zipped the two lists :

labels = []
texts = [] 
#function that fills the lists.
values = zip(labels,results)
context = {'values': values }  
return render(request,'mypage.html',context)

Then in my template I have tried this :

{% for value in values %}
<ul>
<li> {{value}}.</li>
</ul>

But this renders a page with:

  • ('label1', 'text1')
  • ('label2', 'text2')

I have also tried to have a dictionary with the labels as keys and texts as values, it renders fine, but then the order is not respected since it's a dict. Ihave thought of other ways of doing it, such as having two dictionaries on for the first row and another for the second row, but my since my knowledge in python and django's templates is not consistent enough I don't know how to do this.

If anyone can help, would be much appreciated.

EDIT : Actually I found the answer two minuts after asking this, but I'll leave it in case it could help anyone. In the template, I just did :

{% for labels, texts in values %}
<ul>
<li> {{labels}} : {{texts}}.</li>
</ul>
{% endfor %}
like image 792
sarahm Avatar asked Jul 29 '13 08:07

sarahm


1 Answers

Use str.join:

values = [" : ".join(x) for x in zip(labels,results)]

And pass this list to template.

With just zip you need to do unpacking inside the template:

values = zip(labels,results)

{% for label, text in values %}
<ul>
<li> {{ label }} : {{ text }}</li>
</ul>
like image 164
Ashwini Chaudhary Avatar answered Oct 25 '22 23:10

Ashwini Chaudhary