首页 > 解决方案 > 使用 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 显示的表格,类似于上面显示的内容?

我无法访问列表中字符串中的值

标签: pythonhtmllistfileflask

解决方案


将数据传递给模板渲染器,然后在模板内循环渲染,假设这是您的模板,名为 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时,您将看到您的模板出现。


推荐阅读