3

I currently have this for loop inside my template:

{% for i in 1234|make_list %}

I would like to obtain something like this inside loop:

{{ form.answer_{{ i }} }}

I am aware that the above line is not valid (it raises TemplateSyntaxError), but I would like to know if there is any way to use the value of i as part my other variable name.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195

1 Answers1

4

First, you would need a custom template filter to mimic getattr() functionality, see:

Then, you would need add template filter for string concatenation:

{% load getattribute %}

{% for i in 1234|make_list %}    
    {% with "answer_"|add:i as answer %}
        {{ form|getattribute:answer }}
    {% endwith %}
{% endfor %}
Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195