Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django use value of template variable as part of another variable name

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.

like image 729
Gabriel Ivascu Avatar asked Jan 17 '26 03:01

Gabriel Ivascu


1 Answers

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

  • Performing a getattr() style lookup in a django template

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 %}
like image 139
alecxe Avatar answered Jan 19 '26 16:01

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!