in my Django 1.1.1 application I've got a function in the view that returns to his template a range of numbers and a list of lists of items, for example:
... data=[[item1 , item2, item3], [item4, item5, item6], [item7, item8, item9]] return render_to_response('page.html', {'data':data, 'cycle':range(0,len(data)-1])
Inside the template I've got an external for loop, that contains also another for cycle to display in output the contains of the inner lists of data in this way
... {% for page in cycle %} ... < table > {% for item in data.forloop.counter0 %} < tr >< td >{{item.a}} < /td > < td > {{item.b}} ... < /td > < /tr > ... < /table > {% endfor %} {% if not forloop.last %} < div class="page_break_div" > {% endif %} {% endfor %} ...
But Django template engine doesn't work with the forloop.counter0
value as index for the list (instead it does if I manually put a numeric value as index). Is there a way to let the list loop works with the external forloop.counter0
value? Thanks in advance for the help :)
I solved this in a rather inefficient way. Please don't throw up on your computer when you read this code. Given two lists of identical length, it will iterate through the first and print the corresponding item from the second.
If you must use this, only use it for rarely-accessed templates where the length of both lists will be small. Ideally, refactor your template's data to avoid this problem altogether.
{% for list1item in list1 %} {% for list2item in list2 %} {% if forloop.counter == forloop.parentloop.counter %} {{ list1item }} {{ list2item }} {% endif %} {% endfor %} {% endfor %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With