Custom counter in django template

I have this code on django template page

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

I want a value for each parameter tag, which is incremented at each iteration. If I have 10 option tags, then their values ​​will be from 0 to 9. forloop.counter0does not correspond to my need, since the internal loop counter is initialized to 0, when the external loop ends once.

+4
source share
2 answers

How to pass an object itertools.countto a template?

Template:

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

View:

import itertools
import functools

render(request, 'template.html', {
    question_groups: ...,
    counter: functools.partial(next, itertools.count()),
})
+1
source

Restore this message to provide solutions using only the template language.

, {% for %} ( ), forloop.parentloop. , , , , (forloop.parentloop.parentloop...).

{% for foo in foos %}
  {% for bar in bars %} {# exactly one for loop between here #}
    {{ forloop.parentloop.counter0 }} is the index of foo. 
  {% endfor %}
{% endfor %}

(, , , django-crispy-forms), :

{% for foo in foos %}
  {% with foo_num=forloop.counter0 %}
    {% for bar in bars %} {# any number of for loops between #}
      {{ foo_num }} is the index of foo. 
    {% endfor %}
  {% endwith %}
{% endfor %}

Falsetru , for, , , . , itertools falsetru.

{% for foo in foos %}
  {{ counter }} is the index of foo
{% endfor %}
{% for bar in bars %}
  {{ counter }} is the index of bar + len(foos)
{% endfor %}
0

Source: https://habr.com/ru/post/1618374/


All Articles