Last active
November 29, 2021 02:03
-
-
Save connerxyz/46d7cb22392705b478eb4cd782952c7e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Remove *all* default, hard-coded, CSS classes and inline styling attached to tables when calling df.to_html(), | |
and add your own classes to each tag ad hoc. | |
This will probably be extremely simple in the future when the styling API is more mature. For now, we bleach it. | |
May need to `conda install bleach` or `pip install bleach` | |
""" | |
import pandas as pd | |
import bleach | |
def bleached_df_table(df, class_map={}): | |
result = df.to_html(escape=False) | |
result = bleach.clean( | |
result, | |
tags=['table', 'thead', 'tbody', 'tr', 'th', 'td'], | |
strip=True | |
) | |
for k, v in class_map.items(): | |
result = result.replace( | |
"<{}>".format(k), | |
"<{} class='{}'>".format(k, v) | |
) | |
return result | |
# Basic example usage | |
df = pd.DataFrame([[1,2], [3,4]]) | |
bleached_df_table(df, clasmap={'table': 'my-special-table-class'}) | |
# Jinja based template example (this is assuming the function is available to the template-context) | |
{{ bleached_df_table(df, class_map={'table': 'my-special-table-class'}) | safe }} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment