【问题标题】:How to render lists of column values into a table using a template (such as Jinja2)如何使用模板(如 Jinja2)将列值列表呈现到表中
【发布时间】:2013-05-14 01:39:54
【问题描述】:

我正在尝试执行以下操作(不起作用,只是为了传达预期的行为):

<table>
  <tr>
    <th>Column 1</th>
    <th>Column 2</th>
    <th>Column 3</th>
  </tr>

  {% for col1_val in col1_values %}
    <tr>
      <td>{{ col1_val }}</td>
      <td>{{ col2_values[col1_values.index(col1_val)] }}</td>
      <td>{{ col3_values[col1_values.index(col1_val)] }}</td>
    </tr>
  {% endfor %}
</table>

所需的表在哪里:

Column 1       Column 2       Column 3
col1_values[0] col2_values[0] col3_values[0]
col1_values[1] col2_values[1] col3_values[1]
.
.
.

col1_values 彼此唯一。

应该如何重写 Jinja2 模板以实现所需的表格输出?是否可以不必转置 col1_values、col2_values 和 col3_values 的维度?如果不是,那么最 Pythonic 的转置方式是什么?

【问题讨论】:

  • 不是{{ col1_val }}吗?不是。
  • 是的,你是对的,谢谢。已经更正了。
  • 为什么不使用嵌套列表呢? table_values = [[col1_value_0, col2_value_0, col3_value_0], [col1_value_1, col2_value_1, col3_value_1], ...]? zip() 函数可以根据需要合并 3 个 colX_values 列表。
  • @MartijnPieters 我将zip(col1_values,col2_values,col3_values)row_values 的形式传递给模板,并从{% for row in row_values %} 循环中以row.0row.1row.2 的形式访问了表格元素,它运行良好.非常感谢!

标签: python html templates jinja2


【解决方案1】:

为什么不使用嵌套列表呢?循环结构如下:

table_values = [[col1_value_0, col2_value_0, col3_value_0], [col1_value_1, col2_value_1, col3_value_1], ...]

zip() function 可以根据需要组合 3 个 colX_values 列表:

table_rows = zip(col1_values, col2_values, col3_values)

现在您可以循环遍历每行列表:

{% for col1_val, col2_val, col3_val in table_rows %}
  <tr>
    <td>{{ col1_val }}</td>
    <td>{{ col2_val }}</td>
    <td>{{ col3_val }}</td>
  </tr>
{% endfor %}

【讨论】:

    【解决方案2】:

    我认为您有三个列表 col1_values、col2_values 和 col3_values。在视图中,将列表构造为:

    col_values = zip(col1_values, col2_values, col3_values)
    

    将 col_values 传递给模板并执行以下操作:

    <table>
      <tr>
        <th>Column 1</th>
        <th>Column 2</th>
        <th>Column 3</th>
      </tr>
    
      {% for col1, col2, col3 in col_values %}
        <tr>
          <td>{{ col1 }}</td>
          <td>{{ col2 }}</td>
          <td>{{ col3 }}</td>
        </tr>
      {% endfor %}
    </table>
    

    我认为这将是解决您的问题的简单方法。希望对您有所帮助。

    【讨论】:

    • 我试过了,但在 for 循环中出现解包错误:“ValueError: too many values to unpack”
    • 你确定你的代码中有这个:col_values = [col1_values, col2_values, col3_values]。其中 col1_values、col2_values、col3_values 应该是列表。
    • 是的,我认为您的代码只是缺少 zip() 步骤...col_values = zip(col1_values, col2_values, col3_values) 有效。
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签