Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
8 changes: 6 additions & 2 deletions folium/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -413,8 +413,12 @@ def remove_empty(**kwargs: TypeJsonValue) -> dict[str, TypeJsonValueNoNone]:


def escape_backticks(text: str) -> str:
"""Escape backslashes and backticks so text can be used in a JS template."""
return text.replace("\\", "\\\\").replace("`", "\\`")
"""Escape text so it can be placed inside a JS template literal.

Backslashes, backticks and ``${`` are escaped, so the text is kept as-is
instead of ending the literal or being evaluated as an interpolation.
"""
return text.replace("\\", "\\\\").replace("`", "\\`").replace("${", "\\${")


def escape_double_quotes(text: str) -> str:
Expand Down
18 changes: 18 additions & 0 deletions tests/test_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,24 @@ def test_popup_backslashes():
assert normalize(rendered) == normalize(expected)


@pytest.mark.parametrize("parse_html", [False, True])
def test_popup_template_literal_interpolation(parse_html):
m = Map()
popup = Popup("price: ${price}", parse_html=parse_html).add_to(m)
rendered = popup._template.render(this=popup, kwargs={})
assert "price: \\${price}" in rendered
assert "price: ${price}" not in rendered


def test_tooltip_template_literal_interpolation():
m = Map()
marker = Marker([0, 0]).add_to(m)
tooltip = Tooltip("price: ${price}").add_to(marker)
rendered = tooltip._template.module.script(this=tooltip, kwargs={})
assert "price: \\${price}" in rendered
assert "price: ${price}" not in rendered


def test_tooltip_backslashes_and_backticks():
m = Map()
marker = Marker([0, 0]).add_to(m)
Expand Down
16 changes: 16 additions & 0 deletions tests/test_utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
_is_url,
camelize,
deep_copy,
escape_backticks,
escape_double_quotes,
get_obj_in_upper_tree,
if_pandas_df_convert_to_numpy,
Expand Down Expand Up @@ -271,6 +272,21 @@ def test_image_to_url_svg(tmp_path):
assert image_to_url(str(path)).startswith("data:image/svg+xml;base64,")


@pytest.mark.parametrize(
"text,result",
[
("bla", "bla"),
("a`b", r"a\`b"),
(r"a\b", r"a\\b"),
("${x}", r"\${x}"),
("$5 and {x}", "$5 and {x}"),
(r"\${x}", r"\\\${x}"),
],
)
def test_escape_backticks(text, result):
assert escape_backticks(text) == result


@pytest.mark.parametrize(
"text,result",
[
Expand Down
Loading