Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template counter in nested loops

Hi I have a list of two dictionaries I am passing to a Django template:

base_parts = [
    {'important item': 43},
    {'lesser item': 22, 'lesser item': 3, 'lesser item': 45}
]

in my template I can do this:

{% for base_part in base_parts %}
    {% for k, v in base_part.items %}

    {# ...do stuff #}

    {# I try to get a running total of items to use as an ID #}
    inner ID: {% forloop.counter0 %}< br/>
    outer ID: {% forloop.parentloop.counter0 %}< br/>

    {% endfor %}
{% endfor %}

As you can see, what I want is a running total of the total number of items I have iterated through, but both methods I have included return duplicates. I know I could concatenate the loops, but I am using a formset and really would like the ids to be indexed 0,1,2...etc.

Is there a way to achieve this type of count in the template?

Any help much appreciated.

EDIT

output at the moment looks like:

outerID: 0<br />
innerID: 0<br />
outerID: 0<br />
innerID: 1<br />
outerID: 1<br />
innerID: 0<br />
outerID: 1<br />
innerID: 1<br />
outerID: 1<br />
innerID: 2<br />

I want:

totalID: 0<br />
totalID: 1<br />
totalID: 2<br />
totalID: 3<br />
totalID: 4<br />
totalID: 5<br />
totalID: 6<br />
totalID: 7<br />
totalID: 8<br />
totalID: 9<br />
like image 460
Darwin Tech Avatar asked Dec 14 '12 00:12

Darwin Tech


2 Answers

UPDATE: This is not a correct answer. I am just keeping it here to display what doesn't work.

I have to admit that i haven't tried this one but you can use with and add statements.

{% with total=0 %}
    {% for base_part in base_parts %}
        {% for k, v in base_part.items %}

        {# ...do stuff #}

        {# I try to get a running total of items to use as an ID #}
        totalId: {{ total|add:"1" }} <br/>
        {% endfor %}
    {% endfor %}
{% endwith %}

This would probably work on template level but i think a better approach is calculating it on the view level and passing a dictionary to the template which includes calculated values.

like image 115
username Avatar answered Nov 08 '22 10:11

username


In an ideal world, you should avoid putting this kind of logic in the template. If you are not preserving the hierarchy in your output (eg displaying these items as a list of lists) flatten the list and use a simple for loop and the loop counter.

However, the ideal solution isn't always an option. In theory, I believe the following could/should work

{% for base_part in base_parts %}     
    {% with outerCounter = forloop.parentloop.counter0 %}
    {% for k, v in base_part.items %}
        ...
        {% with innerCounter = forloop.counter %}
        {{ outerCounter|add:innerCounter }}
    {% endfor %}
{% endfor %}
like image 45
Enrico Avatar answered Nov 08 '22 11:11

Enrico