【问题标题】:django template turn array into HTML tabledjango模板将数组转换为HTML表格
【发布时间】:2012-02-22 01:46:44
【问题描述】:

我有一个包含 16 个结果的列表,我们称之为“结果”。我想把它们排列在一个 4 x 4 的桌子上。

使用 django 模板,我该怎么做? (这里似乎循环对我没有帮助)

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

谢谢!!

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    您可以为此使用cycle 标签。

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

    会输出类似...

    <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>
    

    【讨论】:

      【解决方案2】:

      你需要构建这样的东西

      <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>
      

      前提是你有这样的数组(实际上是字典)

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

      有很多这样做的。这是最直接的方法。查看 Django 模板标签文档。

      这是我从头到尾学到的技术列表。还有更多,但我没有时间记录所有这些。 http://binarybugs01.appspot.com/entry/template-iteration-techniques

      有时您必须小心传递给模板的上下文字典。 如果你通过了这个

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

      您正在迭代result.result,键是result.result.name


      我还想提醒您,您有一个列表、一个集合、一个字典或一个元组。但是,您可以导入数组并使用它。

      【讨论】:

      • not result.name 我认为它的 r.name 和 r.time, r.address,r.date {% for r in result %} {{ result.name } } {{ result.address }} {{ result.time }} {{ result.date }} {% endfor %}
      【解决方案3】:

      假设你有:
      results=[[1, 2, 3, 4,], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

      以下模板可用于在表格中显示结果:

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

      它将显示:

      1  2  3  4
      5  6  7  8
      9  10 11 12
      13 14 15 16
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-30
        • 2015-10-30
        • 2017-05-07
        • 2021-04-02
        • 1970-01-01
        • 2016-08-26
        相关资源
        最近更新 更多