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
3 changes: 2 additions & 1 deletion folium/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -1852,7 +1852,8 @@ def __init__(self, popup: IFrame | Html | str | None = None):
if isinstance(popup, Element):
popup = popup.render()
if popup:
self.popup = "`" + escape_backticks(popup) + "`" # type: ignore
# ${lat} and ${lng} are documented placeholders, so keep them.
self.popup = "`" + escape_backticks(popup, interpolate=True) + "`" # type: ignore
else:
self.popup = '"Latitude: " + lat + "<br>Longitude: " + lng '

Expand Down
15 changes: 12 additions & 3 deletions folium/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -412,9 +412,18 @@ def remove_empty(**kwargs: TypeJsonValue) -> dict[str, TypeJsonValueNoNone]:
return {key: value for key, value in kwargs.items() if value is not None}


def escape_backticks(text: str) -> str:
"""Escape backslashes and backticks so text can be used in a JS template."""
return text.replace("\\", "\\\\").replace("`", "\\`")
def escape_backticks(text: str, interpolate: bool = False) -> str:
"""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.
Pass ``interpolate=True`` to leave ``${...}`` untouched, for templates
that are meant to fill in JS variables.
"""
text = text.replace("\\", "\\\\").replace("`", "\\`")
if not interpolate:
text = text.replace("${", "\\${")
return text


def escape_double_quotes(text: str) -> str:
Expand Down
7 changes: 7 additions & 0 deletions tests/test_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,13 @@ def test_geojson_from_utf8_file(tmp_path, encoding):
assert GeoJson(str(path)).data == data


def test_click_for_marker_keeps_lat_lng_placeholders():
m = Map()
click = ClickForMarker("<b>Lat:</b> ${lat}<br /><b>Lon:</b> ${lng}").add_to(m)
rendered = click._template.module.script(this=click, kwargs={})
assert "`<b>Lat:</b> ${lat}<br /><b>Lon:</b> ${lng}`" in rendered


# GeoJsonMarker type validation.
def test_geojson_marker():
m = folium.Map([30.4, -97.5], zoom_start=10)
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
20 changes: 20 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,25 @@ 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


def test_escape_backticks_interpolate():
assert escape_backticks("a`b ${lat}", interpolate=True) == r"a\`b ${lat}"


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