python – django模板中的自定义计数器

我在
django模板页面中有这个代码

<select class="selectpicker datatable-column-control" multiple
{% for q_group in question_groups %}
    <optgroup label="{{ q_group.name }}">
    {% for q in  q_group.questions %}
        <option value="{{ forloop.counter0 }}">{{ q.title }}</option>
    {% endfor %}
    </optgroup>
{% endfor %}

我希望每个迭代中增加的每个选项标记都有一个值.如果我有10个选项标签,那么它们的值将从0到9.
forloop.counter0不能满足我的需要,因为当外循环完成一次时内循环计数器初始化为0.

最佳答案 如何将
itertools.count对象传递给模板?

模板:

<select class="selectpicker datatable-column-control" multiple>
{% for q_group in question_groups %}
    <optgroup label="{{ q_group.name }}">
    {% for q in  q_group.questions %}
        <option value="{{ counter }}">{{ q.title }}</option>
    {% endfor %}
    </optgroup>
{% endfor %}
</select>

视图:

import itertools
import functools

render(request, 'template.html', {
    question_groups: ...,
    counter: functools.partial(next, itertools.count()),
})
点赞