Django template turn an array into an HTML table

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

Using the django template, how can I do this? (It seems to me that the loop will not help me here)

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

Thanks!!

+7
source share
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> 

Print 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> 
+17
source

You need to build something like this

 <table> <tr> <th>header1</th> <th>header2</th> <th>header3</th> <th>header4</th> </tr> {% for r in result %} <tr> <th> {{ result.name }}</th> <th> {{ result.address }}</th> <th> {{ result.time }}</th> <th> {{ result.date }}</th> </tr> {% endfor %} </table> 

provided that you have an array (actually a dictionary) this way

 result['name'] result['address'] result['time'] result['date'] return render_to_response("my_template.html", {'result:result'}) 

There are several ways to do this. This is the easiest way. Check out the documentation for the Django template template.

Here is a list of techniques that I have learned throughout. There are more of them, but I don’t have time to document them all. http://binarybugs01.appspot.com/entry/template-iteration-techniques

Sometimes you need to be careful with the context dictionary that you pass into the template. If you pass this

 result = {'name': 'John', 'time': '12/2/2012'....etc} context['result'] = result return render_to_response("my_template.html", context} 

You repeat result.result , and the keys result.result.name


I also want to remind you that you have a list, set, dictionary, or tuple. However, you can import the array and use it.

+8
source

All Articles