Reputation: 615
I have a list that is passed into a template. I want to access a value with a specific index. Problem is the list is accessed with dot notation in the template...
For example:
object = { id: 1 }
list = [ "zero", "one" ]
print list[ object.id ] ## one
Once the list is in the template you access values by index with dot notation.
list.1 ## one
list[ object.id ] ## this doesn't work
list.object.id ## this doesn't work obv.
How can I access the value "one" with the index of "1"?
Thanks in advance!
Upvotes: 1
Views: 2261
Reputation: 689
I don't quite agree it's impossible.
You can create template tag, which will accept two arguments and will inject a new variable into a template context.
The usage can look as follows: {% get_list_member list object.id as list_member %}
then you can use list_member as ordinary template variable {{ list_member }}
check the implementation of standard url template tag, which also allows to assign url into template context variable for later use.
Upvotes: 1
Reputation: 182093
I don't think this is possible with Django's template language. It is pretty limited by design.
You can do this by putting that code in the view, and passing the value of list[object.id]
down to the template when you render it.
Upvotes: 2