Home how to use integer variable as subscript in Django template
Reply: 2

how to use integer variable as subscript in Django template

Sandi Published in 2018-01-11 17:55:24Z

I have a for loop in a Django template:

{% for i in no_of_lift_series_range %}
    {{ workout.lifts.series.i.activity_name }}
{% endfor %}

where this fails to output anything. The problem lies in the use of i. I know this, because this:

{% for i in no_of_lift_series_range %}
    {{ workout.lifts.series.0.activity_name }}
{% endfor %}

outputs what it is supposed to output. Why can't I use i in the way I want and how do I make this work?

Ivan Reply to 2018-01-11 19:19:07Z

I would create custom template filter to get the list item by index:

def get_by_index(mylist, index):
    return mylist[index]

You could use it like this:

{% for i in no_of_lift_series_range %}
    {% with item=workout.lifts.series|get_by_index:i %}
        {{ item.activity_name }}
    {% endwith %}
{% endfor %}
Arnoux Reply to 2018-01-11 19:14:21Z

Your logic seems a bit off. Perhaps you should be doing something like this instead:

{% for activity in workout.lifts.series %}
    {% with forloop.counter as count %}
        {{ count }} - {{ activity.activity_name }}
    {% endwith %}
{% endfor  %}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.333948 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO