【问题标题】:Iterate and print elements for 2d arrays in Jinja syntax在 Jinja 语法中迭代和打印二维数组的元素
【发布时间】:2021-11-10 06:22:00
【问题描述】:

我想迭代一个二维数组来打印一个单元格中的每个元素,我该如何在 jinja 中编写这个?

到目前为止,我的代码仅在单个单元格中打印每一行(包含三个元素):

Data: [[90,50,30],
       [40,20,70],
       [60,80,10]]

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

预期输出:

No Value of Row 1 Value of Row 2 Value of Row 3
1 90 50 30
2 40 20 70
3 60 80 10

【问题讨论】:

    标签: python for-loop flask multidimensional-array jinja2


    【解决方案1】:

    将您的模板更改为:

    <div class="container">
      <table class="table">
          <thead>
              <th>No</th>
              <th>Value of Row 1</th>
              <th>Value of Row 2</th>
              <th>Value of Row 3</th>
          </thead>
          <tbody>
            {% for row in data %}
            <tr>
            <td>{{ loop.index }}</td>
            {% for cell in row %}
              <td>{{ cell }}</td>
              {% endfor %}
            </tr>
            {% endfor %}
    </div>
    

    【讨论】:

    • 注意,你可能还想使用循环来构造表头。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    相关资源
    最近更新 更多