How do I add serial number in table data in flask?

0

Issue

I have a table, in which I am inserting data using Jinja 2 via for loop. Now I am having trouble adding the serial number. If I add 2nd loop for it (it becomes nested), it duplicates the table rows.

Here is my code:

<table class="table-auto w-full text-left whitespace-no-wrap">
          <thead>
            <tr>
              <th class="px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100 rounded-tl rounded-bl">Sr</th>
              <th class="px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100">Semester</th>
              <th class="px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100">GPA</th>
             
            
            </tr>
          </thead>
          <tbody>

            {%for key, value in gpa_list.items()%}
            <tr>
              <td class="border-t-2 border-gray-200 px-4 py-3"># I want to add serial here</td>
              <td class="border-t-2 border-gray-200 px-4 py-3">{{key}}</td>
              <td class="border-t-2 border-gray-200 px-4 py-3">{{value}}</td>
            </tr>
            
            {% endfor %}
            
          </tbody>
        </table>

Please tell me a way to add serial number in first <td>.

Solution

If by serial number you mean automatically generated numbers starting from 1, you would use jinja2’s magic {{loop.index}}. This is normally achieved in Python by using the built-in enumerate function, but jinja2 templates are not simply running embedded Python.

<table class="table-auto w-full text-left whitespace-no-wrap">
  <thead>
    <tr>
      <th class="px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100 rounded-tl rounded-bl">Sr</th>
      <th class="px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100">Semester</th>
      <th class="px-4 py-3 title-font tracking-wider font-medium text-gray-900 text-sm bg-gray-100">GPA</th>

    </tr>
  </thead>
  <tbody>

    {%for key, value in gpa_list.items()%}
    <tr>
      <td class="border-t-2 border-gray-200 px-4 py-3">{{loop.index}}</td>
      <td class="border-t-2 border-gray-200 px-4 py-3">{{key}}</td>
      <td class="border-t-2 border-gray-200 px-4 py-3">{{value}}</td>
    </tr>
    
    {% endfor %}
    
  </tbody>
</table>

Answered By – Evan

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More