Skip to content

ENH: escape html argument in Styler.format #40437

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Mar 23, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 40 additions & 5 deletions pandas/io/formats/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
from pandas.core.indexes.api import Index

jinja2 = import_optional_dependency("jinja2", extra="DataFrame.style requires jinja2.")
from jinja2.filters import escape as escape_func

BaseFormatter = Union[str, Callable]
ExtFormatter = Union[BaseFormatter, Dict[Any, Optional[BaseFormatter]]]
Expand Down Expand Up @@ -113,6 +114,10 @@ class Styler:

.. versionadded:: 1.2.0

escape : bool, default False
Replace the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in cell display
strings with HTML-safe sequences.

Attributes
----------
env : Jinja2 jinja2.Environment
Expand Down Expand Up @@ -169,6 +174,7 @@ def __init__(
cell_ids: bool = True,
na_rep: Optional[str] = None,
uuid_len: int = 5,
escape: bool = False,
):
# validate ordered args
if isinstance(data, pd.Series):
Expand Down Expand Up @@ -201,7 +207,7 @@ def __init__(
] = defaultdict(lambda: partial(_default_formatter, precision=None))
self.precision = precision # can be removed on set_precision depr cycle
self.na_rep = na_rep # can be removed on set_na_rep depr cycle
self.format(formatter=None, precision=precision, na_rep=na_rep)
self.format(formatter=None, precision=precision, na_rep=na_rep, escape=escape)

def _repr_html_(self) -> str:
"""
Expand Down Expand Up @@ -547,6 +553,7 @@ def format(
subset: Optional[Union[slice, Sequence[Any]]] = None,
na_rep: Optional[str] = None,
precision: Optional[int] = None,
escape: bool = False,
) -> Styler:
"""
Format the text display value of cells.
Expand All @@ -570,6 +577,12 @@ def format(

.. versionadded:: 1.3.0

escape : bool, default False
Replace the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in cell display
string with HTML-safe sequences. Escaping is done before ``formatter``.

.. versionadded:: 1.3.0

Returns
-------
self : Styler
Expand Down Expand Up @@ -639,8 +652,27 @@ def format(
0 1 2
0 MISS 1.0000 STRING
1 2.0 MISS FLOAT

Using a formatter with HTML ``escape``.

>>> df = pd.DataFrame([['<div></div>', '"A&B"']])
>>> s = df.style.format('<a href="a.com/{0}">{0}</a>', escape=True)
>>> s.render()
...
<td .. ><a href="a.com/&lt;div&gt;&lt;/div&gt;">&lt;div&gt;&lt;/div&gt;</a></td>
<td .. ><a href="a.com/&#34;A&amp;B&#34;">&#34;A&amp;B&#34;</a></td>
...

"""
if all((formatter is None, subset is None, precision is None, na_rep is None)):
if all(
(
formatter is None,
subset is None,
precision is None,
na_rep is None,
escape is False,
)
):
self._display_funcs.clear()
return self # clear the formatter / revert to default and avoid looping

Expand All @@ -658,7 +690,7 @@ def format(
except KeyError:
format_func = None
format_func = _maybe_wrap_formatter(
format_func, na_rep=na_rep, precision=precision
format_func, na_rep=na_rep, precision=precision, escape=escape
)

for row, value in data[[col]].itertuples():
Expand Down Expand Up @@ -2154,6 +2186,7 @@ def _maybe_wrap_formatter(
formatter: Optional[BaseFormatter] = None,
na_rep: Optional[str] = None,
precision: Optional[int] = None,
escape: bool = False,
) -> Callable:
"""
Allows formatters to be expressed as str, callable or None, where None returns
Expand All @@ -2170,9 +2203,11 @@ def _maybe_wrap_formatter(
raise TypeError(f"'formatter' expected str or callable, got {type(formatter)}")

if na_rep is None:
return formatter_func
na_func = formatter_func
else:
return lambda x: na_rep if pd.isna(x) else formatter_func(x)
na_func = lambda x: na_rep if pd.isna(x) else formatter_func(x)

return (lambda x: na_func(escape_func(x))) if escape else na_func


def _maybe_convert_css_to_tuples(style: CSSProperties) -> CSSList:
Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/io/formats/style/test_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,17 @@ def test_format_clear(self):
self.styler.format()
assert (0, 0) not in self.styler._display_funcs # formatter cleared to default

def test_format_escape(self):
df = DataFrame([['<>&"']])
s = Styler(df, uuid_len=0).format("X&{0}>X", escape=False)
ex = '<td id="T__row0_col0" class="data row0 col0" >X&<>&">X</td>'
assert ex in s.render()

# only the value should be escaped before passing to the formatter
s = Styler(df, uuid_len=0).format("X&{0}>X", escape=True)
ex = '<td id="T__row0_col0" class="data row0 col0" >X&&lt;&gt;&amp;&#34;>X</td>'
assert ex in s.render()

def test_nonunique_raises(self):
df = DataFrame([[1, 2]], columns=["A", "A"])
msg = "style is not supported for non-unique indices."
Expand Down