views:

518

answers:

2

Hi, 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 :)

+1  A: 

You can't use variables for attribute names, dictionary keys or list indizes.

Also range(0,len(data)-1] is not valid python. It should be range(len(data)).

You probably don't need cycle. Maybe what you want is this:

{% for itemlist in data %}
    ...
    <table>
        {% for item in itemlist %}
        < tr >< td >{{item.a}} < /td > < td > {{item.b}} ... < /td > < /tr >
        ...
        {% endfor %}
    </table>
    {% if not forloop.last %}
        <div class="page_break_div">
    {% endif %}
{% endfor %}
stefanw
Thanks Stefanw, it's exactly what I was trying to do, I didn't think about iterate over the list because in the case of `len(data)==1` (yes, the one I wrote before wasn't a good python statement) I had to show the list output in a different way. Anyway now seems all is working, thanks again for your help!
Alex
A: 

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