Access tuple in django template

Rajeev picture Rajeev · Mar 7, 2011 · Viewed 29.5k times · Source
 t=[]
 t.append(("a",1))
 t.append(("b",2))
 t.append(("c",3))
 return render_to_response(t.html,  context_instance=RequestContext(request, {'t':t}))

If i want access access a value of t in django templates without using a for loop how can i do it.I have tried the following and it doesnt seem to work

    alert('{{t[a]}}');
    alert('{{t[c]}}');

Answer

Ofri Raviv picture Ofri Raviv · Mar 7, 2011

Assuming your view code is:

t=[]
t.extend([('a',1),('b',2),('c',3)])

(and not as stated in the OP)

{{ t.0.0 }} is like t[0][0] in Python code. This should give you "a", because t.0 is the first element of the list t, which itself is a tuple, and then another .0 is the tuple's first element.

{{ t.0.1 }} will be 1, and so on.

But in your question you are creating a tuple and trying to access it as if it is a dict.

That's the problem.