Django 模板标签和元编程:有没有办法在调用上下文之前修改变量的名称?

Django Template Tags and Meta-Programming: Is there any way of modifying a variable's name before calling its context?

假设在 views.py 中,我的上下文中有可变(即变化)数量的对象形式或类型。 (为了简单起见,我只使用 'forms' 这个词)。

context = {
     'form_0': form_0,
     'form_1': form_1,
     'form_2': form_2,
     'form_3': form_3,
     # ... and so forth
}

假设我无法知道在任何给定时间我的上下文中有多少种形式。是否可以使用模板标签执行以下操作:

{% for i in (number of forms in context) %}

{{ form_i }} <-- where i is equal to the number i in the loop -->

{% endfor %}

这里的最终结果将转换为:

{{ form_0 }}
{{ form_1 }}
{{ form_2 }}
... and so forth

我怀疑这是否可行,但如果可行,我会发现它很有帮助。

按名称引用,如构造包含名称的字符串,通常被认为是一种不安全方法:它可能比人们想象的更难构造一个算法来构造正确命名。 Forthermore 说你这样做然后删除 form_3,那么你的算法可能会在 2 处停止,但也许那里还有其他形式,但你忘记了算法获取形式。

这里最好传递一个collection对象,例如list:

context = {
    <b>'forms'</b>: <b>[</b>form_0, form_1, form_2, form_3<b>]</b>
}

然后我们可以在模板中渲染它:

{% for form_i in <b>forms</b> %}
    {{ form_i }}
{% endfor %}

如果您因此向列表中添加一个额外的表单,那么该表单将成为模板中迭代的一部分,因此 Django 将呈现该表单(或您放入列表中的任何内容)。

如果您还需要访问某些特定的表单,您也可以通过另一个名称传递,例如:

context = {
    'forms': [form_0, form_1, form_2, form_3],
    # if we need specific items of form_2 in the template,
    # we can pass it under a specific name as well
    'form_2': form_2
}

所以现在我们都可以枚举 forms 来呈现这些,但是如果 form_2 有一些我们需要在模板中处理的有趣数据,我们仍然可以使用 {{ form_2.non_field_errors }} 例如。