2

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?

9
  • 1
    Why can't you just iterate through workout.lifts.series? Commented Jan 11, 2018 at 17:59
  • 1
    You could also use the forloop.counter0 docs Commented Jan 11, 2018 at 18:35
  • @DanielRoseman because I need i for other purposes in the loop Commented Jan 11, 2018 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 Commented Jan 12, 2018 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. Commented Jan 13, 2018 at 17:42

2 Answers 2

4

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

@register.filter
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 %}
Sign up to request clarification or add additional context in comments.

Comments

-2

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  %}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.