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

how to use integer variable as subscript in Django template

user9173
1#
user9173 Published in September 19, 2018, 3:18 am

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?

share|improve this question
  • 1
    Why can't you just iterate through workout.lifts.series? – Daniel Roseman Jan 11 at 17:59
  • 1
    You could also use the forloop.counter0 docs – Philipp Zettl Jan 11 at 18:35
  • @DanielRoseman because I need i for other purposes in the loop – Sahand Jan 11 at 18:37
  • 1
    To update, forloop.counter0 cannot be used since I need i in order to do numeric index acces with it, which doesn't seem possible in django templates – Sahand Jan 12 at 9:06
  • 1
    @Sandi you have to think about "i" as a String, as a literal. When you say {{ object.0 }} Django tries to do: getattr(object, "0") and if it fails it tries to do this: object[int("0")]. But your variable "i" will be interpreted as getattr(object, "i"), it'll look for that name, not it's content. – wm3ndez Jan 13 at 17:42

2 Answers 2

active oldest votes
up vote 2 down vote accepted
You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO