首页 > 解决方案 > 有没有办法在 python 烧瓶中按单元格设置表格属性?

问题描述

我正在尝试使用 python 烧瓶动态创建 html 表。我知道在烧瓶文档(https://flask-table.readthedocs.io/en/stable/)中,它说您可以将属性传递给 td 和 th html 元素,但这仅允许您在列中传递内容使用 td_html_attrs、th_attml_attrs 和 columns_html_attrs 参数的级别,而不是单元级别。例如,如果我有 3 列,我只能设置 3 个不同的 td/th 属性。我正在寻找一种将唯一 td/ th 属性传递给表格中各个单元格的方法。

下面是我现在拥有的python代码。它创建了一个烧瓶项目,该项目具有转到相应页面的 onclick 属性,但是您可以看到是否在 localhost:5000(默认端口)的浏览器(我使用的是 chrome)中运行它/打开烧瓶应用程序,您不能指定特定单元格的属性,只能指定列。

from flask import Flask, render_template, Markup
from flask_table import Table, Col
app = Flask(__name__)

d_tda = {"onclick":"location.href='https://google.com';"}
d_tdb = {"onclick":"location.href='https://yahoo.com';"}
d_tdc = {"onclick":"location.href='https://bing.com';"}

class ItemTable(Table):
    a = Col("a",td_html_attrs=d_tda)
    b = Col("b",td_html_attrs=d_tdb)
    c = Col("c",td_html_attrs=d_tdc)

class Item(object):
    def __init__(self,a,b,c):
        self.a= a
        self.b= b
        self.c= c

@app.route('/')
def results():
    items = [Item('r1c1','r1c2','r1c3'),
             Item('r2c1','r2c2','r2c3'),
             Item('r3c1','r3c2','r3c3')]

    table = ItemTable(items) # items will be a list of item objects, each item will create a row in the table

    return render_template("results.html", table=Markup(table.__html__()))

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

^ 该 python 文件(称为 app.py)必须与名为“templates”的文件夹位于同一目录中,并且该“templates”文件夹必须包含一个名为“results.html”的文件,该文件将包含以下内容:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    {{ table }}
</body>
</html>

然后,您可以从 app.py 文件所在目录中的终端/命令行运行该应用程序,其中包含以下内容:

python "app.py"

标签: pythonhtmlflaskflask-table

解决方案


推荐阅读