3

I'm using the bootstrap.min.css for stylesheets in my Flask app and am styling the data tables outputted by Pandas in the following manner:

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

Everything is working very well and stylings are applied as hoped. One thing I cannot figure out is how to also add in the .thead-light or dark styling to this?

I'm using these as resources

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

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

I've tried adding to this part classes='table table-striped table-hover' something like classes='table table-striped table-hover thead-light' but that styling doesn't appear.

Any suggestions on how to style my table so the header has that styling applied in the Flask app (hopefully without having to write additional .css)?

2 Answers 2

3

The DataFrame.to_html method only supports adding classes to the table element itself, so there's no way to apply a class to the thead from Python.

A workaround for this would be to use javascript to apply the desired class when the page loads. Just add this script to your template, before the </body> end tag:

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

This will add the thead-light class to the <thead> of every table with class table on your page.

Sign up to request clarification or add additional context in comments.

1 Comment

Works well. (I used jquery)
0

In case you don't want to use JS you can also use string.replace():

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

First header only:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.