【问题标题】:Is it possible to use Django forloop.counter in this case? [duplicate]在这种情况下可以使用 Django forloop.counter 吗? [复制]
【发布时间】:2013-03-23 14:55:47
【问题描述】:

我想像这样使用Django forloop.counter

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

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

这样做的原因。我有 20 个数据库列,例如:time_code1、time_code2 ....time_code20。所以,我不想单独调用每个,而是这样做。

【问题讨论】:

标签: django django-templates


【解决方案1】:

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

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 %}

【讨论】:

    【解决方案2】:

    我用过类似的方式。举个例子,不知道有没有用。

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

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

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

    【讨论】:

      猜你喜欢
      • 2016-11-07
      • 2018-05-05
      • 1970-01-01
      • 2022-11-14
      • 2013-11-14
      • 2012-03-28
      • 1970-01-01
      • 1970-01-01
      • 2016-09-12
      相关资源
      最近更新 更多