[Django] forloop.counterで外のループのカウンターの値を取得する方法

Python

Djangoを勉強し始めてから2週間ほど経ちますが、Templeteでプログラミング的な書き方があまりできず四苦八苦しています(追記: custom template tagsとcustom template filtersを後に知りました)。

forloop.counterは、templateのfor文の中でインクリメントの変数の代わりに使えますが、ネストしたfor文の外側のカウンターの値を取得するにはどう書けばいいのか調べてみました。

外のループのカウンターの値は{{forloop.parentloop.counter}}で取得できます。

{% for item in items %}
    <p>{{ item.content }}</p>
    {% for num in nums %}
        <label><input type="radio" name="group{{forloop.parentloop.counter}}" value="{{ num }}">{{ num }}</label>
    {% endfor %}
{% endfor %}

広告