Sarmad Ali
Sarmad Ali

Reputation: 25

Iterate Multiple Nested Lists in Flask Template using For loop

I have Python list like the following

[[1, 'sarmad ali', 10], [2, 'nabeel', 200], [3, ' tayyab', 40202]]

I want to show them in a table/two dimensional style in template(html page) the following

1 sarmad ali 10

2 nabeel 200

3 tayyab 40202

I am able to got the following

1 sarmad ali 10 2 nabeel 200 3 tayyab 40202

In my python file I have data in the form of Dataframe, and converted to list.

{% for col in data_list%}
    
    {% for row in col%}
        
        <td>{{row}}</td>
    
    {% endfor %}
    
    <br>

{% endfor %}

The above nested loop is producing the output in single line instead of table format. I figured out that second loop is iterating all the lists in single line instead of iterating single list at a time

Feel free to ask any question for more clarification.

Upvotes: 0

Views: 1435

Answers (2)

NavaneethaKrishnan
NavaneethaKrishnan

Reputation: 1318

<table>
{% for sno, name, rank in data_list%}
   <tr>
     <td>{{sno}}</td>
     <td>{{name}}</td>
     <td>{{rank}}</td>
  </tr>
{% endfor %}
</table>

Edited: Suppose if you don't know the number of items in the list,

<table>
{% for tr in data_list%}
   <tr>
   {% for td in data_list%}
     <td>{{td}}</td>
    {% endfor%}
  </tr>
{% endfor %}
</table>

Upvotes: 1

Ebrahim Bharmal
Ebrahim Bharmal

Reputation: 16

This is what i am using in my template file to display the list.

<div class="content-section">
    <legend class="mb-4"> Table </legend>
<table class="table" >
<thead>
    <tr>
      <th scope="col">#</th>
      {%for i in columns%}
      <th scope="col">{{i[0]}}</th>
      {%endfor%}
    </tr>
  </thead>
  <tbody>

    {%for i in result%}

    <tr>
          <th scope="row">{{loop.index}}</th>
          {%for k in i%}
          <td>{{k}}</td>
          {%endfor%}
      </tr>

    {%endfor%}
    </tbody>
</table>

</div>

Upvotes: 0

Related Questions