Johnny Metz
Johnny Metz

Reputation: 5965

Using rowspan while iterating

Let's say I have the following two lists:

names = ['Josh', 'Brad', 'Jordan']
favorite_colors = [['blue', 'red'], ['purple', 'gold', 'yellow'], ['green', 'pink']]

That is to say, Josh's favorite colors are blue and red, Brad's are purple and gold, etc.

I'm passing this data to a jinja2 template via flask and I'm looking to throw it all in a table. I want the table to look like so: https://jsfiddle.net/46qqfef5/

As you can see, I'm using the rowspan attribute to group name and color. However, when I try to iterate over the data using the jinja2 code below the <td rowspan="2"> tag appears in EVERY row (and I need it to only appear the first time a new name occurs).

jinja2:

<div class="table-responsive">
  <table class="table table-bordered table-hover">
    <thead>
      <tr>
        <th>Name</th>
        <th>Favorite Color</th>
      </tr>
    </thead>
    <tbody>
      {% for name_index in range(names | count) %}
        {% for color_index in range(favorite_colors[name_index] | count %}
          <tr>
            <td rowspan="{{ favorite_colors[name_index] | count }}">{{ names[name_index] }}</td>
            <td>{{ favorite_colors[name_index][color_index] }}</td>
          </tr>
        {% endfor %}
      {% endfor %}
    </tbody>
  </table>
<div

If I remove rowspan={{ ... }} from the jinja2 code above I get the following table but that looks pretty awful to me: https://jsfiddle.net/46qqfef5/3/

I need a way to print the name cell for only the first occurrence of a new name.

Upvotes: 0

Views: 3772

Answers (1)

Sergey Shubin
Sergey Shubin

Reputation: 3257

You can use special loop variables for checking if current loop is first. In your case loop.first can be used:

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Favorite Color</th>
    </tr>
  </thead>
  <tbody>
  {% for name_index in range(names | count) %}
    {% for color in favorite_colors[name_index] %}
    <tr>
      {% if loop.first %}
      <td rowspan="{{ favorite_colors[name_index] | count }}">
        {{ names[name_index] }}
      </td>
      {% endif %}
      <td>{{ color }}</td>
    </tr>
    {% endfor %}
  {% endfor %}
  </tbody>
</table>

Upvotes: 4

Related Questions