Django使用模板变量的值作为另一个变量名的一部分 [英] Django use value of template variable as part of another variable name
本文介绍了Django使用模板变量的值作为另一个变量名的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前在我的模板中有这个for循环:
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 }} }}
我知道上面一行是无效的(它引发了TemplateSyntaxError),但是我想知道是否有任何方法使用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.
推荐答案
首先,您需要一个自定义模板过滤器以模拟 getattr()
功能,请参阅:
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 %}
这篇关于Django使用模板变量的值作为另一个变量名的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文