Django模板:获取嵌套循环的总迭代次数

时间:2010-12-03 23:31:30

标签: django django-templates

我在模板中有两个嵌套的for循环。我需要获得自父for循环开始以来的总迭代次数。只有当子进行迭代时,才需要递增计数器。

例如:

每个循环从1到3(包括)

父循环 - 第一次迭代

子循环 - 第三次迭代

通缉结果:3

父循环 - 第二次迭代

子循环 - 第一次迭代

通缉结果:4

我有什么方法可以使用标准的Django模板标签吗?如果没有,我的选择是什么?

4 个答案:

答案 0 :(得分:2)

Write a count template tag将累积在上下文变量中。

{% for ... %}
  {% for ... %}
    {% count totalloops %}
  {% endfor %}
{% endfor %}
{{ totalloops }}

答案 1 :(得分:1)

你知道吗,进去,会有多少循环?

如果是这样,一个简单的方法是:

{{forloop.counter | add:forloop.parentcounter.counter}}等。

对于逻辑分离来说有点臭(@ Ignacio的建议在这方面肯定更好),但我认为如果保持整洁有序,这是可以接受的。

答案 2 :(得分:1)

要么你可以使用{{forloop.counter | add:forloop.parentcounter.counter}}但是如果要重置计数器则依赖于这种情况然后你需要编写自己的自定义python方法然后你可以调用它来自django模板。

在你的观点中添加 -

class make_incrementor(object):
    count = 0

    def __init__(self, start):
        self.count = start

    def inc(self, jump=1):
        self.count += jump
        return self.count

    def res(self):
        self.count = 0
        return self.count

def EditSchemeDefinition(request, scheme_id):

    iterator_subtopic = make_incrementor(0)
    scheme_recs = scheme.objects.get(id=scheme_id)
    view_val = {
        'iterator_subtopic': iterator_subtopic,
        "scheme_recs": scheme_recs,
    }
    return render(request, "edit.html", view_val)

稍后在你的django模板中我们可以调用" iterator_subtopic"增加或重置其值的方法如: -

<td id="subTopic" class="subTopic">
<p hidden value="{{ iterator_subtopic.res }}"></p>
{% for strand in  scheme_recs.stand_ids.all %}
    {{ iterator_subtopic.res }}
    {% for sub_strand in  strand.sub_strand_ids.all %}
        {% for topic in  sub_strand.topic_ids.all %}
            {% for subtopic in  topic.sub_topic_ids.all %}
                <input id="subTopic{{ iterator_subtopic.inc  }}" class="len"
                       value="{{ subtopic.name }}">
                <br>
            {% endfor %}
        {% endfor %}
    {% endfor %}
{% endfor %}

所以它会不断增加值,我们也可以将它重置到我们想要的地方。

答案 3 :(得分:0)

使用基于类的视图(特别是使用Python 3和Django 2.1),并使用@Javed的答案作为起点,您可以在视图中执行以下操作:

class Accumulator:

    def __init__(self, start=0):
        self.reset(start)

    def increment(self, step=1):
        step = 1 if not isinstance(step, int) else step
        self.count += step
        return self.count

    def reset(self, start=0):
        start = 0 if not isinstance(start, int) else start
        self.count = start
        return self.count

class MyView(ParentView):

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['counter'] = Accumulator()  # use start=-1 for a zero-based index.
        return context

然后在模板中,您可以执行以下操作:

{% with counter.increment as count %}
  <input id="form-input-{{ count }}">
{% endwith %}