python - Django 使用模板变量的值作为另一个变量名的一部分

标签 python django variables django-templates

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

{% for i in 1234|make_list %}

我想在内部循环中获得类似这样的东西:

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

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

最佳答案

首先,您需要一个 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 %}

关于python - Django 使用模板变量的值作为另一个变量名的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27324602/

相关文章:

使用请求库的 Django Rest Framework 测试功能

swift - 从另一个类 Swift 访问变量

python - Virtualenv 包含全局包/如何清除我的 PYTHONPATH?

python - 如何使用 doxygen 为所有 python 文件创建文档(和调用图)

python - 为什么 'model' 对象不可迭代?

python - 基于类的 View 中的可选 url 参数

python - "hashable"在 Python 中是什么意思?

python - Ctypes 获取窗口位置

python - 具有变量值的 Django 查询集

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP