park-junha
park-junha

Reputation: 21

How do I render a table from a 2-dimensional array from Python to HTML using Flask?

Say I have a list of lists like:

table = [[1,2,3],[4,5,6],[7,8,9]]

which can be have a dynamic number of lists and I want to render it into my web page like so:

@app.route("/")
def home():
    return render_template('home.html', tbl=zip(*table))

I want to write in my home.html file so that it can write the table. Originally, my web page had:

{% for col1, col2 in tbl %}
    <tr>
        <td>{{ col1 }}</td>
        <td>{{ col2 }}</td>
    </r>
{% endfor %}

where col1 and col2 were arguments originally passed into tbl

tbl=zip(col1, col2)

but I'm not sure how to write the html code so that it can read a dynamic number of columns.

Upvotes: 2

Views: 1482

Answers (1)

Ajax1234
Ajax1234

Reputation: 71451

You do not need to use unpacking when rendering your table as simple iteration will suffice:

<table>
  {%for row in tbl%}
     <tr>
        {%for col in row%}
          <td>{{col}}</td>
        {%endfor%}
     </tr>
  {%endfor%}
</table>

Upvotes: 2

Related Questions