[英]How to structure data to easily build HTML tables in Flask
I am trying to create HTML tables from data stored in a table.我正在尝试从存储在表中的数据创建 HTML 表。 My data is read from a table and converted into a dict of lists, eg:
我的数据是从表中读取并转换为列表字典,例如:
x = {'date':[u'2012-06-28', u'2012-06-29', u'2012-06-30'], 'users': [405, 368, 119]}
My goal is to create an HTML table with the following structure for an arbitrary list length:我的目标是为任意列表长度创建一个具有以下结构的 HTML 表:
<table>
<thead>
<th>Date</th>
<th>Users</th>
</thead>
<tbody>
<tr>
<td>2012-06-28</td>
<td>405</td>
</tr>
<tr>
<td>2012-06-29</td>
<td>368</td>
</tr>
<tr>
<td>2012-06-30</td>
<td>119</td>
</tr>
</tbody>
</table>
I have tried doing this two incorrect ways in my Flask template:我曾尝试在 Flask 模板中以两种不正确的方式执行此操作:
<tbody>
{% for line in x %}
<tr>
<td>{{ x.date|tojson|safe }}</td>
<td>{{ x.users }}</td>
</tr>
{% endfor %}
</tbody>
Which prints the entire list into each column.它将整个列表打印到每一列中。
And:和:
{% for date in x.date %}
<tr><td>{{ date|tojson|safe }}</td></tr>
{% endfor %}
{% for users in x.users %}
<tr><td>{{ users }}</td></tr>
{% endfor %}
Which simply prints everything into the first column.这只是将所有内容打印到第一列中。
These experiments and many other dead ends lead me to believe that there is no simple way to build the table as I would like given my current data structure.这些实验和许多其他死胡同让我相信,鉴于我当前的数据结构,没有简单的方法来构建表。
Given this, I have two questions:鉴于此,我有两个问题:
1) How would I go about building the table using my current data structure? 1)我将如何使用我当前的数据结构来构建表?
2) What is the standard or ideal way to structure data for this use case? 2)为这个用例构建数据的标准或理想方式是什么?
Thanks in advance.提前致谢。
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:或者你可以在 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 %}
您可以使用Flask-Table或更复杂的东西,甚至可以使用Flask-Admin 。
是的,您确实想使用字典列表而不是列表字典,这在 Jinja2 中效果更好
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.