django template turn array into HTML table

痴心易碎 提交于 2019-12-02 21:03:56

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>

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 a number of do this. This is the most straightforward ways. Look at Django template tag documentation.

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

Sometimes you have to be careful with the context dictionary you are passing to the template. If you are passing this

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

You are iterating over result.result and the keys are result.result.name


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!