You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jinja语法中遍历二维数组并将每个元素单独输出至表格单元格

你当前代码的问题是:遍历外层二维数组得到的i是包含3个元素的内层一维数组,直接把整个i输出到3个<td>中,自然会把整行数据重复填充到每个单元格里。

你可以直接通过下标取出内层数组的对应元素即可,调整后的代码如下:

<div class="container">
  <table class="table">
      <thead>
          <tr>
            <th>No</th>
            <th>Value of Row 1</th>
            <th>Value of Row 2</th>
            <th>Value of Row 3</th>
          </tr>
      </thead>
      <tbody>
        {% for i in array %}
        <tr>
          <td>{{ loop.index }}</td>
          <td>{{ i[0] }}</td>
          <td>{{ i[1] }}</td>
          <td>{{ i[2] }}</td>
        </tr>
        {% endfor %}
      </tbody>
  </table>
</div>

注:原代码还存在<thead>下没有包裹<tr>、</tbody>和</table>标签缺失的问题,上述代码已经一并修复。

如果后续你的内层数组长度不固定,也可以用嵌套循环的方式更灵活地生成单元格,写法如下:

<div class="container">
  <table class="table">
      <thead>
          <tr>
            <th>No</th>
            {% for col_name in ['Value of Row 1', 'Value of Row 2', 'Value of Row 3'] %}
            <th>{{ col_name }}</th>
            {% endfor %}
          </tr>
      </thead>
      <tbody>
        {% for row in array %}
        <tr>
          <td>{{ loop.index }}</td>
          {% for item in row %}
          <td>{{ item }}</td>
          {% endfor %}
        </tr>
        {% endfor %}
      </tbody>
  </table>
</div>

内容的提问来源于stack exchange,提问作者manacoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 14:45:11