我想使用 python 燒瓶框架在 html 中顯示一個表格。我有兩個陣列。一個用于列標題,另一個用于資料記錄。列標題和資料記錄的長度是動態的。我可以動態管理列“標題”。但只是將資訊附加到“資料”陣列中并不能正確顯示資料。請幫我解決這個問題。應該更改 html 檔案中的某些內容以使其動態化嗎? 來自燒瓶的Python 檔案匯入 Flask、request、render_template
app = Flask(__name__)
@app.route('/')
def my_form():
#headings = ("name", "role", "salary")
headings = []
headings.append("name")
headings.append("role")
data1 = ("rolf", "software engineer", "4500"), ("neu", "civil engineer", "1500"), ("neu", "civil engineer", "1500")
# =============================================================================
data = []
data.append("rolf")
data.append("software engineer")
data.append("neu")
data.append("civil engineer")
# =============================================================================
print (data1)
print (data)
#ss = '(' '(' "rolf" ',' "software engineer" ',' "4500" ')' ',' ')'
return render_template('table2.html', data=data, headings=headings)
if __name__ == '__main__':
app.run()
.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>

uj5u.com熱心網友回復:
data1是一個元組的元組。
>>> data1 = ("rolf", "software engineer", "4500"), ("neu", "civil engineer", "1500"), ("neu", "civil engineer", "1500")
>>> data1
(('rolf', 'software engineer', '4500'), ('neu', 'civil engineer', '1500'), ('neu', 'civil engineer', '1500'))
data,它變成一個元組串列,在這樣構建時具有完全不同的結構:
>>> data = []
>>> data.append("rolf")
>>> data.append("software engineer")
>>> data.append("neu")
>>> data.append("civil engineer")
>>> data
['rolf', 'software engineer', 'neu', 'civil engineer']
>>>
我想你正在尋找:
>>> data = []
>>> data.append(("rolf","software engineer", "4500"))
>>> data.append(("neu","civil engineer", "1500"))
>>> data
[('rolf', 'software engineer', '4500'), ('neu', 'civil engineer', '1500')]
也許這不是表示資料的最佳方式。不過,在這個問題的背景下很難給出進一步的建議。
我猜這只是為了教育目的,你知道在其他型別的實作中,這些資訊可能是從資料庫中檢索的,或者來自 API 回應,而不是在這樣的py檔案中靜態定義。
uj5u.com熱心網友回復:
對于您的資料,顯然您希望生成一個像這樣的元組串列:
>>> data = []
>>> row = tuple()
>>> row = ('rolf',)
>>> row = ('software engineer',)
>>> row = (4500,)
>>> row
('rolf', 'software engineer', 4500)
>>> data.append(row)
>>> data
[('rolf', 'software engineer', 4500)]
>>>
還有你的 HTML 代碼:
<table>
<thead>
<tr>
{% for header in headings %}
<th>{{ header }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for row in data %}
<tr>
{% for cell in row %}
<td>{{ cell }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/405691.html
標籤:
