Home > database >  how to use integer value from for loop to get a list element in django template
how to use integer value from for loop to get a list element in django template

Time:03-30

I have a list of numbers in views.py list=[0,1,2,3,4,5] (it is not the same all the time I'm fetching it from API) then in my search.html I have written the following code:-

{% for i in list %}
    <a href="https://example.com//{{ id[i] }}">
      <img  src="https://this.isapi.org/{{poster[i]}}" alt="" />
      <h4>{{title[i]}}</h3>
    </a>
{% endfor %}

where the id, poster, title are lists passed through views.py

I want to get elements of each list 1 by 1 I tried adding for loop for each but the result was bad all posters render first and then titles were rendering I want to know how can I use it to call items from the list or any other by which I can access elements for all lists in a single loop.

I have also tried {% with abcd=i %} but the result was the same keep getting this error

Could not parse the remainder: '[i]' from 'id[i]'

CodePudding user response:

To achieve that, first create your own filter:

@register.filter
def get_index(lst, i):
    return lst[i]

Which you can then use in your template like:

{% for i in list %}
    <a href="https://example.com//{{ id|get_index:i }}">
      <img  src="https://this.isapi.org/{{poster|get_index:i}}" alt="" />
      <h4>{{title|get_index:i}}</h3>
    </a>
{% endfor %}

For information on how to register custom tags look here.

  • Related