【问题标题】:Django use value of template variable as part of another variable nameDjango 使用模板变量的值作为另一个变量名的一部分
【发布时间】:2015-02-04 03:17:58
【问题描述】:

我目前在我的模板中有这个 for 循环:

{% for i in 1234|make_list %}

我想在循环内获得类似的东西:

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

我知道上面的行无效(它会引发 TemplateSyntaxError),但我想知道是否有任何方法可以将 i 的值用作我的其他变量名的一部分。

【问题讨论】:

    标签: python django variables django-templates


    【解决方案1】:

    首先,您需要一个 custom template filter 来模仿 getattr() 功能,请参阅:

    然后,您需要add template filter 进行字符串连接:

    {% load getattribute %}
    
    {% for i in 1234|make_list %}    
        {% with "answer_"|add:i as answer %}
            {{ form|getattribute:answer }}
        {% endwith %}
    {% endfor %}
    

    【讨论】:

    • 非常感谢您指导我
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 2012-03-30
    • 2020-07-10
    • 2014-04-29
    • 1970-01-01
    相关资源
    最近更新 更多