Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django template turn array into HTML table

I have a list of 16 results, let's call it "results". I want to arrange them in a 4 x 4 table.

Using the django template, how can I do this? (It doesn't seem like cycle would help me here)

<table>
{% for r in results %}
...?
{% endfor %}
</table>

Thanks!!

like image 961
Bill VB Avatar asked Feb 22 '12 01:02

Bill VB


People also ask

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What is Forloop counter in Django?

A for loop is used for iterating over a sequence, like looping over items in an array, a list, or a dictionary.

What is Django's built in URL template tag?

What is URL Template Tag? The URL template tag is a typical type of Tag in the Django Template Language framework. This tag is specifically used to add View URLs in the Template Files.


2 Answers

You can use the cycle tag for this.

<table>
  {% for r in results %}
    {% cycle '<tr>' '' '' '' %}
      <td>{{r.content}}</td>
    {% cycle '' '' '' '</tr>' %}
  {% endfor %}
</table>

Would output something like...

<table>
  <tr>
    <td>result 1</td>
    <td>result 2</td>
    <td>result 3</td>
    <td>result 4</td>
  </tr>
  <tr>
    <td>result 5</td>
    <td>result 6</td>
    <td>result 7</td>
    <td>result 8</td>
  </tr>
  <!-- etc -->
</table>
like image 67
Thomas Avatar answered Sep 19 '22 21:09

Thomas


Suppose you have:
results=[[1, 2, 3, 4,], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

The following template can be used to display results in a table:

<table>
  {% for rowval in results %}    
     <tr>
     {% for val in rowval %}
      <td>{{val}}</td>
     {% endfor %}
    </tr>
  {% endfor %}
</table> 

It will display:

1  2  3  4
5  6  7  8
9  10 11 12
13 14 15 16
like image 22
Roohollah Etemadi Avatar answered Sep 17 '22 21:09

Roohollah Etemadi