Django dynamically change index in template -


i have following code in template:

{% test in page.object_list %}     <tr>         <td colspan="2" class="testsuite">{{ test.name.0 }}</td>         <td class="testsuite">failed: {{ percentages.0 }}%</td>    </tr> {% endfor %} 

where test.name.0 name of test suite , percentages list of failed test cases inside test suite. wondering how might able change percentages.0 percentages.i i incremented on each iteration of for loop.

update
after trying @gocht's answer have following code:

in template tags/get_percentage.py file

from django import template register = template.library()  @register.filter def get_percentage(percentage_list, i):     return percentage_list[int(i)] 

and in template

{% load get_percentage %} {% test in page.object_list %}     <tr>         <td colspan="2" class="testsuite">{{ test.name.0 }}</td>         <td class="testsuite">failed: {{ percentages|get_percentage: forloop.counter0 }}%</td>     </tr> {% endfor %} 

and running "string index out of range" error. tried looking possible causes none of answers related custom template tags.

i assume missed in question percentages.0 instead percentages.i. in for on template, can access index forloop variable. this:

{% test in page.object_list %}     {{ forloop.counter }}   # start @ 1     {{ forloop.counter0 }}  # start @ 0     # here {% endfor %} 

see: this answer


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -