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?
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 }}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With