How to structure data to easily build HTML tables in Flask

Like you said, you could either change your data structure, or change your template code. Here is one way to keep the current structure:

{% for row_index in range(x['date']|count) %}
    <tr>
      <td>{{ x[row_index]['date']|tojson|safe }}</td>
      <td>{{ x[row_index]['users'] }}</td>
    </tr>
{% endfor %}

Or you could restructure your data in python:

x = zip(x['date'], x['users'])

And then use this template:

{% for row in x %}
    <tr>
      <td>{{ row[0]|tojson|safe }}</td>
      <td>{{ row[1] }}</td>
    </tr>
{% endfor %}

You can also structure the data so that the template does not depend on the order of the cells:

from itertools import izip
x = [dict(date=d, user=u) for d, u in izip(x['date'], x['users'])]

Then you can access your data like this:

{% for row in x %}
    <tr>
      <td>{{ row['date']|tojson|safe }}</td>
      <td>{{ row['user'] }}</td>
    </tr>
{% endfor %}

You might use Flask-Table or for something more complex even leverage Flask-Admin.

Tags:

Python

Html

Flask