python - 使用 Python 为特定行创建一个包含多列的 HTML 表
问题描述
我写了这段代码:
tr = ""
for author, projects in data.iteritems():
tr + = "<tr><td>{}</td>".format(author)
for project, branches in projects.iteritems():
tr += "<td>{}</td>".format(project)
for branch in branches:
tr += "<td>{}</td>".format(branch)
tr += </td></tr>
end = "</table>"
我有这个数据集
{
'user_one': {'project_a': ['branch_1', 'branch_2'],
'project_b': ['branch_1']},
'user_two': {'project_x': ['branch_x1', 'branch_b'] }
}
我想打印如下表:
+-------------------------------------------+
| User | Project | Branch |
+------------+---------------+--------------+
| user_one | project_a | branch_1 |
+------------+---------------+--------------+
| | | branch_2 |
+------------+---------------+--------------+
| | project_b | branch_1 |
+------------+---------------+--------------+
| user_two | project_x | branch_x1 |
+------------+---------------+--------------+
| | | branch_b |
+------------+---------------+--------------+
如果它的单个项目工作正常,但当涉及多个项目时,它不会。我可以使用 PrettyTable 获得结果,但因为我希望 project_a、_b、_x 等成为超链接。我在使用 PrettyTable 时无法实现,所以我开始编写自己的基于数据的 html 生成器。
解决方案
除了琐碎的 HTML(可能不是表格),我建议使用模板库。
我会选择Jinja2。它的语法非常简单和直观(如果您见过任何其他模板语言),它有很好的文档记录,并且非常流行(=更多 SO 支持)。
呈现表格的示例。
<table class="table table-striped">
<thead><tr>
<th>One</th>
<th>Two</th>
<th>Three</th>
<th>Four</th>
</tr></thead>
<tbody>
{% for row in tabular_data %}
<tr>
<td>{{ row.one }}</td>
<td>{{ row.two }}</td>
<td>{{ row.three }}</td>
<td>{{ row.four }}</td>
</tr>
{% endfor %}
</tbody>
</table>
如果您使用的是 Web 框架,它可能是开箱即用的,如果没有,则只需几行即可渲染它:
from jinja2 import Environment, FileSystemLoader # pip install Jinja2
env = Environment(loader=FileSystemLoader("/path/to/templates/folder")
template = env.get_template("TableTemplate.html") # the template file name
html = template.render(**context_data)
context_data
包含所需数据的字典在哪里。在上面的示例中,它需要一个tabular_data
字段来保存具有属性的对象(或字典)数组one
,two
...:
context_data = {
# Row = namedtuple("Row", ["one", "two", "three", "four"])
'tabular_data': [
Row(1, 2, 3, 4),
Row("a", "b", "c", "d"),
...,
]
}
推荐阅读
- react-native - 在本机反应中禁用提交按钮
- spring-boot - Spring Boot @EnableEurekaClient 有条件
- facebook - 通过 Facebook Graph-API 访问 Instagram
- javascript - Google maps API/Geocoding Uncaught ReferenceError: google is not defined
- python - 响应 400
在 Dreamfactory API POST 调用上 - php - 使用 Sessions 在 Web 应用程序中处理长时间且耗时的 ajax 调用
- java - 在 Native SQL Hibernate 中使用 addJoin 的列中出现异常
- javascript - Javascript:单击图像时播放音频
- javascript - Express JS 用接收到的图像渲染视图
- python - 我正在使用乳齿象 python api,我正在尝试从输出字典中访问用户名。但它无法访问