P
P
Pan Propan2016-04-26 18:10:45
Django
Pan Propan, 2016-04-26 18:10:45

Is it possible to get the forloop.counter of the outer loop?

I use Django-Mptt.
There is a nested loop, I need to get the counter value of the outer loop in the nested loop

<table class="table">
    {% for category in categorys %}
        {% if category.is_leaf_node %}
        <tr class="treegrid-{{ forloop.counter }}">
            <td>{{ category.name }}</td>
        </tr>
            {% for product in category.get_products %}
                <tr class="treegrid-{{ forloop.counter|add:1 }} treegrid-parent-{{ forloop.counter }}">
                    <td>{{ product.title }}</td>
                </tr>
            {% endfor %}
        {% endif %}
    {% endfor %}
    </table>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pan Propan, 2016-04-26
@mgis

Everything is already in the documentation .
See the forloop.parentloop method
- For nested loops, this is the “outer” loop.

A
Alexey Cheremisin, 2016-04-26
@leahch

So?

<table class="table">
    {% for category in categorys %}
        {% if category.is_leaf_node %}
        <tr class="treegrid-{{ forloop.counter }}">
{% set outer_counter = forloop.counter %}
            <td>{{ category.name }}</td>
        </tr>
            {% for product in category.get_products %}
                <tr class="treegrid-{{ forloop.counter|add:1 }} treegrid-parent-{{ outer_counter }}">
                    <td>{{ product.title }}</td>
                </tr>
            {% endfor %}
        {% endif %}
    {% endfor %}
    </table>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question