From b2a51f65eca53b13d53bf670f2eb4c2db954fc82 Mon Sep 17 00:00:00 2001 From: Xiaokang Fu <1072534112@qq.com> Date: Sun, 22 Jan 2023 06:18:38 -0500 Subject: [PATCH] BUG: Escape special characters in explore (#2657) (#2658) --- CHANGELOG.md | 1 + geopandas/explore.py | 14 +++++++++++++- geopandas/tests/test_explore.py | 9 +++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 04eef7b..d3b3782 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ Bug fixes: - Ensure that GeoDataFrame created from DataFrame is a copy, not a view (#2667) - Fix mismatch between geometries and colors in ``plot()`` if an empty or missing geometry is present (#2224) +- Escape special characters to avoid TemplateSyntaxError in ``explore()`` (#2657) - Fix `to_parquet`/`to_feather` to not write an invalid bbox (with NaNs) in the metadata in case of an empty GeoDataFrame (#2653) diff --git a/geopandas/explore.py b/geopandas/explore.py index 4fa6820..21b93d0 100644 --- a/geopandas/explore.py +++ b/geopandas/explore.py @@ -278,6 +278,7 @@ GON (((180.00000 -16.06713, 180.00000... try: import branca as bc import folium + import re import matplotlib import matplotlib.colors as colors import matplotlib.pyplot as plt @@ -618,10 +619,21 @@ GON (((180.00000 -16.06713, 180.00000... else: tooltip = None popup = None + # escape the curly braces {{}} for jinja2 templates + feature_collection = gdf.__geo_interface__ + for feature in feature_collection["features"]: + for k in feature["properties"]: + # escape the curly braces in values + if type(feature["properties"][k]) == str: + feature["properties"][k] = re.sub( + r"\{{2,}", + lambda x: "{% raw %}" + x.group(0) + "{% endraw %}", + feature["properties"][k], + ) # add dataframe to map folium.GeoJson( - gdf.__geo_interface__, + feature_collection, tooltip=tooltip, popup=popup, marker=marker, diff --git a/geopandas/tests/test_explore.py b/geopandas/tests/test_explore.py index 285cc90..3e7c05d 100644 --- a/geopandas/tests/test_explore.py +++ b/geopandas/tests/test_explore.py @@ -466,6 +466,15 @@ class TestExplore: out_str = self._fetch_map_string(m) assert "BoroName" in out_str + def test_escape_special_characters(self): + # check if special characters are escaped + gdf = self.world.copy() + gdf["name"] = """{{{what a mess}}} they are so different.""" + m = gdf.explore() + out_str = self._fetch_map_string(m) + assert """{{{""" in out_str + assert """}}}""" in out_str + def test_default_markers(self): # check overridden default for points m = self.cities.explore()