Access tuple in django template

33,459

Solution 1

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.

Solution 2

You can convert your tuple to dict via dict() function:

mydict = dict(t)

And then in template you can access items by key like here:

{{ mydict|get_item:item.NAME }}
Share:
33,459
Rajeev
Author by

Rajeev

Updated on April 22, 2021

Comments

  • Rajeev
    Rajeev about 3 years
     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}))
    

    How can I access a value of t in Django templates without using a for loop? I have tried the following and it doesn't seem to work:

        alert('{{t[a]}}');
        alert('{{t[c]}}');
    
  • Rajeev
    Rajeev about 13 years
    cant we access the values from the keys namely a,b,c??
  • Ofri Raviv
    Ofri Raviv about 13 years
    You can, but you'll have to make t a dict: t = {'a':1,'b':2,'c':3}, then t.a should work.