Html表显示不正确

fwzugrvs  于 2023-05-21  发布在  其他
关注(0)|答案(1)|浏览(112)

我正在尝试显示一个包含囚犯信息的表。
我使用Flask和Jinja将数据从python文件传递到html文档:

headings = ("First", "Last", "Court Date", "Bond Amount", "Bond Paid", "Charges")
data = (
        ("Carl", "Johnson", "12/12/2023", 1200, 900, "Murder"),
        ("Joe", "Lewis", "10/22/2023", 2000, 890, "Theft"),
        ("Jarod", "Green", "11/29/2023", 1900, 700, "Robbery") 
    )

@views.route("/info/")
def info():
    return render_template("info.html", headings=headings, data=data)

我的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>

我的html文档在页面上显示以下内容:
{%for header in heads %} {%endfor%} {%for row in data%} {%for cell in row%} { %endfor%}{ % endfor%} {{ header }}{{ cell }}
它根本没有显示表,只有jinja代码。
谁能告诉我我哪里错了。

kyvafyod

kyvafyod1#

我在你的问题上工作,它在我这边工作这里是链接到存储库,你可以找到我使用的所有文件,https://github.com/HarunMbaabu/StackOveflow-Answered-Question/tree/main/flask_table_not_displaying_correctly
确保你已经连接好了HTML和Flask服务器文件,建议使用templates文件夹。下面是我的代码:
Python文件:

from flask import Flask, render_template, url_for

views = Flask(__name__) 

#Route Example
@views.route("/")
def index():
    # Define the base URL
    base_url = "http://127.0.0.1:5000"
    
    # Create the link URL
    info_url = f"{base_url}/info"

    return f"Test your table info endpoint here your endpoint at <a href='{info_url}'>{info_url}</a>"

#Relevant Code for your question start here
headings = ("First", "Last", "Court Date", "Bond Amount", "Bond Paid", "Charges")

data = (
        ("Carl", "Johnson", "12/12/2023", 1200, 900, "Murder"),
        ("Joe", "Lewis", "10/22/2023", 2000, 890, "Theft"),
        ("Jarod", "Green", "11/29/2023", 1900, 700, "Robbery") 
    )

@views.route("/info/")
def info():
    return render_template("info.html", headings=headings, data=data)
#Relevant code for your question ends here

if __name__ == '__main__':
    views.run(debug=True)

templates/info.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>

输出:

相关问题