【问题标题】:Bootstrap CSS and pandas DataFrame.to_html. How to add class to <thead>?引导 CSS 和 pandas DataFrame.to_html。如何向 <thead> 添加类?
【发布时间】:2020-05-11 22:06:48
【问题描述】:

我在我的 Flask 应用程序中使用 bootstrap.min.css 作为样式表,并按以下方式对 Pandas 输出的数据表进行样式设置:

result = pd.DataFrame.from_dict(result, orient='index', columns = [var2use]).to_html(classes='table table-striped table-hover', header = "true", justify = "center")

一切运行良好,样式如期应用。我无法弄清楚的一件事是如何添加.thead-light 或深色样式?

我将这些用作资源

https://getbootstrap.com/docs/4.4/content/tables/

https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.DataFrame.to_html.html

我尝试在此部分添加 classes='table table-striped table-hover' 类似 classes='table table-striped table-hover thead-light' 的内容,但没有出现该样式。

关于如何为我的表格设置样式以使标题在 Flask 应用程序中应用该样式(希望无需编写额外的 .css)有什么建议吗?

【问题讨论】:

    标签: html css pandas flask


    【解决方案1】:

    DataFrame.to_html 方法仅支持向表格元素本身添加类,因此无法从 Python 将类应用于 thead

    解决方法是在页面加载时使用 javascript 应用所需的类。只需将此脚本添加到您的模板中,在 &lt;/body&gt; 结束标记之前:

    <script type='text/javascript'>
      window.onload = function() {
        const thead = document.querySelectorAll('.table > thead');
        thead.forEach(e => e.classList.add('thead-light'));
      }
    </script>
    

    这会将thead-light 类添加到您页面上每个具有table 类的表的&lt;thead&gt; 中。

    【讨论】:

    • 效果很好。 (我用jquery)
    【解决方案2】:

    如果你不想使用 JS 你也可以使用 string.replace():

    df.to_html(classes="table").replace("<thead>", "<thead class='thead-light'>")
    

    仅第一个标题:

    df.to_html(classes="table").replace("<thead>", "<thead class='thead-light'>", 1)
    

    【讨论】:

      猜你喜欢
      • 2017-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-03
      • 2018-12-06
      相关资源
      最近更新 更多