Search code examples
pythonhtmlflaskjinja2

display two python lists in html using jinja template as two columns in web page


I have two python lists:

list_1 = [1, 2, 3, 4, 5, 6, 7]
list_2 = ["A", "B", "C", "D", "E", "F", "G"]

I have tried:

<div class="tableFixHead">
  <table id="data">
    <tr>{% for num in list_1 %}
      <td>{{num}}</td>
    </tr>
    <tr>{% for alp in list_2 %}
      <td>{{alp}}</td>
    </tr>
    {% endfor %}
</div>

With these two lists I want to create a table in a webpage using jinja like below:

wanted table

I can do it when using a single list. But how to do it with multiple lists?


Solution

  • You only have one {% endfor %} for two iterations. This looks wrong, also td and tr elements looks mixed up. What I would recommend is to zip the lists in the backend like this:

    data = zip(list_1, list_2)
    

    and then iterate over these tuple pairs in the frontend:

    <div class="tableFixHead">
      <table id="data">
        {% for num, alp in data %}
        <tr>
          <td>{{ num }}</td>
          <td>{{ alp }}</td>
        </tr>
        {% endfor %}
      </table>
    </div>
    

    (You can use the zip functionality also in the frontend, e.g. via Jinja2 filter, of course.)