python - 使用 Flask 在 html 元素中显示来自 txt 文件的数据
问题描述
我目前有一个文本文件,在文本文件“incorrect_answers.txt”中提交表单后记录“{level number},{name},{answer}” ,如下所示:
1, bob, answerone
1, nicky, answertwo
1, laura, answerthree
使用 Python 和 Flask,我的目标是在 HTML 页面上的表格中显示数据,如下所示:
| Level | Name | Answer |
| 1 | bob | answerone |
| 2 | nicky | answertwo |
| 3 | laura | answerthree |
目前,我正在以下函数中调用文本文件中的数据:
def get_incorrect_answers():
with open("data/incorrect_answers.txt", "r") as file:
incorrect_answers = file.readlines()
return incorrect_answers
这个函数的结果当然是:
['1, bob, answerone\n', '1, nicky, answertwo\n', '1, laura, answerthree\n']
请有人解释操作此输出的最佳方法,以便我得到一个以 HTML 显示的表格,类似于上面显示的内容?
我无法访问列表中字符串中的值
解决方案
将数据传递给模板渲染器,然后在模板内循环渲染,假设这是您的模板,名为 mytable.html
<table>
<thead>
<tr>
{% for subfield in column_names %}
<th>{{ subfield }}</th>
{% endfor %}
</tr>
{% for item in incorrect_answers %}
<tr>
{% for subitem in item %}
<td> {{ subitem }}</td>
</tr>
</thead>
然后你用类似的东西渲染它
@app.route('/incorrect_answers')
def get_incorrect_answers():
with open("data/incorrect_answers.txt", "r") as file:
incorrect_answers = file.readlines()
return render_template('mytable.html', column_names=['Level', 'Name', 'Answer'],
incorrect_answers=incorrect_answers)
当您转到http://localhost:port/incorrect_answers时,您将看到您的模板出现。
推荐阅读
- oracle - Oracle SQL Developer:测试失败:网络适配器无法建立连接?
- java - Intellij 无法使用 Gradle 解析重定位的 Java 导入
- cmd - ipconfig /all 没有列出正确的 dns 服务器
- javascript - Streamsets Javascript脚本错误加载JQuery
- javascript - res.local 通过 Express 传递数组
- java - Android Studio 不显示“app”文件夹
- javascript - JavaScript 和 css 平滑滚动不适用于 ios
- android - 无法使用 Firebase 的 authUI 登录 Google Auth
- qt - 无限 QGraphicsView::resizeEvent 调用
- c# - 从字幕中删除重复或重复的订单号