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

馋奶兔 提交于 2020-01-04 01:57:06

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/27324602/django-use-value-of-template-variable-as-part-of-another-variable-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!