Skip to content

Commit

Permalink
Make sure that tableId is a valid HTML id
Browse files Browse the repository at this point in the history
  • Loading branch information
mwouts committed Mar 5, 2024
1 parent 8f9899e commit 439cadb
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
14 changes: 14 additions & 0 deletions itables/javascript.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,7 @@ def to_html_datatable(
use_to_html=False,
**kwargs,
):
check_table_id(tableId)
if use_to_html or (pd_style is not None and isinstance(df, pd_style.Styler)):
return to_html_datatable_using_to_html(
df=df,
Expand Down Expand Up @@ -399,6 +400,19 @@ def to_html_datatable(
)


def check_table_id(table_id):
"""Make sure that the table_id is a valid HTML id.
See also https://stackoverflow.com/questions/70579/html-valid-id-attribute-values
"""
if table_id is not None:
if not re.match(r"[A-Za-z][-A-Za-z0-9_.]*", table_id):
raise ValueError(
"The id name must contain at least one character, "
f"cannot start with a number, and must not contain whitespaces ({table_id})"
)


def set_default_options(kwargs, use_to_html):
if use_to_html:
options_not_available = set(kwargs).intersection(
Expand Down
8 changes: 8 additions & 0 deletions tests/test_javascript.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from itables.javascript import (
_df_fits_in_one_page,
_tfoot_from_thead,
check_table_id,
replace_value,
to_html_datatable,
)
Expand Down Expand Up @@ -96,3 +97,10 @@ def test_tfoot_from_thead(
""",
):
assert _tfoot_from_thead(thead) == expected_tfoot


def test_check_table_id():
with pytest.raises(ValueError, match="cannot start with a number"):
check_table_id("0_invalid_id")
check_table_id("valid_id")
check_table_id("valid_id-2")

0 comments on commit 439cadb

Please sign in to comment.