doniyor
doniyor

Reputation: 37934

for loop django template logic - how can I do this?

I am trying to output 2 items for each row. I have 4 items coming from db.

<table>
 <tr>
{% for item in items %}
   <td>
  {{item.name}},{{item.size}}
   </td>
{% endfor %}
 </tr>
</table>

this is giving me

name1, 23m^2 | name2,20m^2 | name3,15m^2 | name4,10m^2

but i need

name1, 23m^2 | name2,20m^2
name3,15m^2 | name4,10m^2

each row being contained in separate <tr>. I am stuck how to break the loop and assign new row..

Upvotes: 0

Views: 137

Answers (2)

karthikr
karthikr

Reputation: 99680

Just switch the <tr> and forloop, and also use forloop.counter and divisibleby

Something like this:

{% if items %}
<tr>
{% for item in items %}
     <td>{{item.name}},{{item.size}}</td>
     {% if forloop.counter|divisibleby:2 %}
     </tr>
     <tr>
     {% endif %}
{% endfor %}
</tr>
{% endif %}

Upvotes: 2

nickzam
nickzam

Reputation: 813

You forgot to close <td> tag.

<table>
 <tr>
{% for item in items %}
   <td>
  {{item.name}},{{item.size}}
   </td> <!-- here -->
{% endfor %}
 </tr>
</table>

Upvotes: 0

Related Questions