silvernightstar
silvernightstar

Reputation: 1965

How to render lists of column values into a table using a template (such as Jinja2)

I am trying to do the following (doesn't work, just shown to convey the intended behavior):

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

where the table desired is:

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

where col1_values are unique from each other.

How should the Jinja2 template be rewritten to achieve the desired table output? Is it possible without having to transpose the dimensions of col1_values, col2_values and col3_values? If not, what would be the most Pythonic way of doing the transpose?

Upvotes: 3

Views: 6434

Answers (2)

rajpy
rajpy

Reputation: 2476

I think that you have three lists col1_values, col2_values and col3_values. In views, construct list of lists as:

col_values = zip(col1_values, col2_values, col3_values)

Pass col_values to template and do the following:

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

I think this would be easy method to solve your problem. Hope it helps.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1122162

Why not use a nested list instead? Loop over a structure like:

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

The zip() function can combine the 3 colX_values lists if need be:

table_rows = zip(col1_values, col2_values, col3_values)

Now you have per-row lists to loop over:

{% 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 %}

Upvotes: 4

Related Questions