Skip to content

Instantly share code, notes, and snippets.

@connerxyz
Last active November 29, 2021 02:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save connerxyz/46d7cb22392705b478eb4cd782952c7e to your computer and use it in GitHub Desktop.
Save connerxyz/46d7cb22392705b478eb4cd782952c7e to your computer and use it in GitHub Desktop.
"""
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