在这种情况下是否可以使用Django forloop.counter?

时间:2013-04-02 10:38:28

标签: django django-templates

我想像这样使用Django forloop.counter

{% for i in "xxxxxxxxxxxxxxxxxxxx" %}
    {{ i.time_code{{forloop.counter}} }}
{% endfor %}

事实证明,这是不可能的。

实现这一目标的理由。我有20个数据库coloumns,如:time_code1,time_code2 .... time_code20。因此,我不想单独调用每个,而是想要这样做。

2 个答案:

答案 0 :(得分:0)

我以类似的方式使用过。这是一个例子,不知道它是否会有所帮助。

<form action= "{% url 'result_show' forloop.counter0 %}" method="post">

它的作用是接受forloop.counter0的输出作为视图中方法的参数。它就是这样的。

您是否考虑过将time_code迁移到列表而不是通过forloop.counter访问它们?

答案 1 :(得分:0)

我不确定我是否正确理解你的问题。您想要动态检索属性吗?您可以编写自定义标记:

from django.template import Library

register = Library()

@register.simple_tag
def get_attr(obj, name, default=None):
    return getattr(obj, str(name), default)

然后您可以将属性列表传递给模板:

attrs = ( "time_code"+str(i) for i in xrange(0, 100) )
return render_to_response("test.html", { "attrs": attrs })

最后在你的模板中:

{% for attr in attrs %}
    {% get_attr i attr %}
{% endfor %}
相关问题