yeugeniuss
yeugeniuss

Reputation: 180

Multicolumn table in django template

How to fill multicolumn table in django template? I have list of n elements (let's say just numbers there) and I want to create a table (looks like grid) with 5 cells in a row.

Very easy to create table of 1 column, but to create 5? Of course we assume than list may have arbitrary number of items from zero to couple hundreds.

<tbody>
  {% for item in data.items.all %}
    <tr class="item-{{ item.number }}">{{ item.number }}</tr>
  {% endfor %}
</tbody>

Upvotes: 1

Views: 304

Answers (1)

aprasanth
aprasanth

Reputation: 1099

Try the following code:

View

data = [1,2,3,4,......,99,100]

Template

<table border="1">
  <tbody>
    <tr>
      {% for item in data %}
        {% if forloop.counter|divisibleby:5 %}
          <td>{{ item }}</td>
          </tr>
          <tr>
        {% else %}
          <td>{{ item }}</td>
        {% endif %}
      {% endfor %}
    </tr>
  </tbody>
</table>

This code checks the loop count each time. if it is divisible by 5 then close the current tr tag and add a new one.

This may not be the right way to achieve this.

Hope that helps.

Upvotes: 1

Related Questions