在 python 烧瓶中显示单行 table 的问题

Problem to show single row table in python flask

我想使用 python flask 框架在 html 中显示一个 table。我有两个数组。一个用于列标题,另一个用于数据记录。当我有两个或多个记录时,我能够完美地显示 table 。但是,如果我只有一行,那么 table 编队就不对了。如何解决这个问题?可以帮我解决这个问题吗?

table.py

from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/')
def my_form():

    headings = ("name", "role", "salary")
    data = (("rolf", "software engineer", "4500"), ("neu", "civil engineer", "1500"), ("neu", "civil engineer", "1500"))

    return render_template('table2.html', data=data, headings=headings)

table2.html

<table>
<tr>
{% for header in headings %}
       <th>{{ header }}</th>
        {% endfor %}
    </tr>
    {% for row in data %}
    <tr>
    {% for cell in row %}
    <td>{{ cell }}</td>
    {% endfor %}
    </tr>
    {% endfor %}
</table>

这段代码似乎失败了,一条记录被错误地定义为:

data = (("rolf", "software engineer", "4500")) # incorrect

修复方法是在外部元组中包含尾随逗号,当元组仅包含一项时必须这样做:

data = (("rolf", "software engineer", "4500"),)

'Why'可以在python中显示shell:

>>> data = (("rolf", "software engineer", "4500"))
>>> data
('rolf', 'software engineer', '4500')
>>> data[0]
'rolf'
>>> # etc ...
... 
>>> data = (("rolf", "software engineer", "4500"),)
>>> data
(('rolf', 'software engineer', '4500'),)
>>> data[0]
('rolf', 'software engineer', '4500')
>>> 

在模板中,一个字符串到达​​循环:{% for cell in row %} 其中 cell 是该字符串中的每个字符,而不是内部元组中的单个项目。