Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list item dynamically in django templates

Tags:

I have some loop on the page and need list item depending from loop number.

When I call:

{{ mylist.1 }} {{ mylist.2 }} {{ mylist.3 }} 

all works fine but what I really need is something like:

{% for x in somenumber|MyCustomRangeTag %}     {{ mylist.x }} {% endfor %} 

MyCustomRangeTag gives me Python range() it works and I already have x as number. So x is 1, 2, 3 etc. depending from loop number. Is this possible and how?

like image 659
Goran Avatar asked Jan 20 '12 22:01

Goran


2 Answers

This is not possible directly because Django thinks that "x" is the key to lookup in mylist - instead of the value of x. So, when x = 5, Django tries to look up mylist["x"] instead of mylist[5].

Use the following filter as workaround:

@register.filter def lookup(d, key):     return d[key] 

and use it like

{{ mylist|lookup:x }} 
like image 89
AndiDog Avatar answered Nov 04 '22 08:11

AndiDog


I notice that @e-satis mentioned it, but I think the built-in slice template tag deserves some love.

{{ item | slice:"2" }} #gets the third element of the list 
like image 34
Matt Luongo Avatar answered Nov 04 '22 08:11

Matt Luongo