Skip to content

Commit 0e9ef12

Browse files
committed
Based on review comments
1 parent becda03 commit 0e9ef12

File tree

5 files changed

+83
-52
lines changed

5 files changed

+83
-52
lines changed

folium/folium.py

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import webbrowser
88
from typing import Any, List, Optional, Sequence, Union
99

10-
from branca.element import Figure
10+
from branca.element import Element, Figure
1111

1212
from folium.elements import JSCSSMixin
1313
from folium.map import Evented, FitBounds, Layer
@@ -62,6 +62,23 @@
6262
]
6363

6464

65+
class GlobalSwitches(Element):
66+
_template = Template(
67+
"""
68+
<script>
69+
L_NO_TOUCH = {{ this.no_touch |tojson}};
70+
L_DISABLE_3D = {{ this.disable_3d|tojson }};
71+
</script>
72+
"""
73+
)
74+
75+
def __init__(self, no_touch=False, disable_3d=False):
76+
super().__init__()
77+
self._name = "GlobalSwitches"
78+
self.no_touch = no_touch
79+
self.disable_3d = disable_3d
80+
81+
6582
class Map(JSCSSMixin, Evented):
6683
"""Create a Map with Folium and Leaflet.js
6784
@@ -193,10 +210,9 @@ class Map(JSCSSMixin, Evented):
193210
}
194211
</style>
195212
196-
197213
<script>
198-
L_NO_TOUCH = {{ this.no_touch |tojson}};
199-
L_DISABLE_3D = {{ this.disable_3d|tojson }};
214+
L_NO_TOUCH = {{ this.global_switches.no_touch |tojson}};
215+
L_DISABLE_3D = {{ this.global_switches.disable_3d|tojson }};
200216
</script>
201217
202218
{% endmacro %}
@@ -311,8 +327,7 @@ def __init__(
311327
else:
312328
self.zoom_control_position = False
313329

314-
self.no_touch = no_touch
315-
self.disable_3d = disable_3d
330+
self.global_switches = GlobalSwitches(no_touch, disable_3d)
316331

317332
self.options = remove_empty(
318333
max_bounds=max_bounds_array,

folium/map.py

Lines changed: 35 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from collections import OrderedDict
88
from typing import TYPE_CHECKING, Optional, Sequence, Union, cast
99

10-
from branca.element import Element, Html, MacroElement
10+
from branca.element import Element, Figure, Html, MacroElement
1111

1212
from folium.elements import ElementAddToElement, EventHandler
1313
from folium.template import Template
@@ -454,27 +454,25 @@ class Popup(MacroElement):
454454

455455
_template = Template(
456456
"""
457-
{% macro script(this, kwargs) %}
458-
var {{this.get_name()}} = L.popup({{ this.options|tojavascript }});
459-
460-
{% for name, element in this.html._children.items() %}
461-
{% if this.lazy %}
462-
{{ this._parent.get_name() }}.once('click', function() {
463-
{{ this.get_name() }}.setContent($(`{{ element.render(**kwargs).replace('\\n',' ') }}`)[0]);
464-
});
465-
{% else %}
466-
var {{ name }} = $(`{{ element.render(**kwargs).replace('\\n',' ') }}`)[0];
467-
{{ this.get_name() }}.setContent({{ name }});
468-
{% endif %}
469-
{% endfor %}
470-
471-
{{ this._parent.get_name() }}.bindPopup({{ this.get_name() }})
472-
{% if this.show %}.openPopup(){% endif %};
473-
474-
{% for name, element in this.script._children.items() %}
475-
{{element.render()}}
476-
{% endfor %}
477-
{% endmacro %}
457+
var {{this.get_name()}} = L.popup({{ this.options|tojavascript }});
458+
459+
{% for name, element in this.html._children.items() %}
460+
{% if this.lazy %}
461+
{{ this._parent.get_name() }}.once('click', function() {
462+
{{ this.get_name() }}.setContent($(`{{ element.render(**kwargs).replace('\\n',' ') }}`)[0]);
463+
});
464+
{% else %}
465+
var {{ name }} = $(`{{ element.render(**kwargs).replace('\\n',' ') }}`)[0];
466+
{{ this.get_name() }}.setContent({{ name }});
467+
{% endif %}
468+
{% endfor %}
469+
470+
{{ this._parent.get_name() }}.bindPopup({{ this.get_name() }})
471+
{% if this.show %}.openPopup(){% endif %};
472+
473+
{% for name, element in this.script._children.items() %}
474+
{{element.render()}}
475+
{% endfor %}
478476
"""
479477
) # noqa
480478

@@ -515,6 +513,21 @@ def __init__(
515513
**kwargs,
516514
)
517515

516+
def render(self, **kwargs):
517+
"""Renders the HTML representation of the element."""
518+
for name, child in self._children.items():
519+
child.render(**kwargs)
520+
521+
figure = self.get_root()
522+
assert isinstance(
523+
figure, Figure
524+
), "You cannot render this Element if it is not in a Figure."
525+
526+
figure.script.add_child(
527+
Element(self._template.render(this=self, kwargs=kwargs)),
528+
name=self.get_name(),
529+
)
530+
518531

519532
class Tooltip(MacroElement):
520533
"""

folium/plugins/search.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from folium.elements import JSCSSMixin
44
from folium.features import FeatureGroup, GeoJson, TopoJson
5+
from folium.folium import Map
56
from folium.plugins import MarkerCluster
67
from folium.template import Template
78
from folium.utilities import remove_empty
@@ -122,9 +123,17 @@ def __init__(
122123
self.placeholder = placeholder
123124
self.collapsed = collapsed
124125
self.options = remove_empty(**kwargs)
125-
self.test_params()
126126

127-
def test_params(self):
127+
def test_params(self, keys):
128+
if keys is not None and self.search_label is not None:
129+
assert self.search_label in keys, (
130+
f"The label '{self.search_label}' was not " f"available in {keys}" ""
131+
)
132+
assert isinstance(
133+
self._parent, Map
134+
), "Search can only be added to folium Map objects."
135+
136+
def render(self, **kwargs):
128137
if isinstance(self.layer, GeoJson):
129138
keys = tuple(self.layer.data["features"][0]["properties"].keys())
130139
elif isinstance(self.layer, TopoJson):
@@ -136,8 +145,6 @@ def test_params(self):
136145
) # noqa
137146
else:
138147
keys = None
148+
self.test_params(keys=keys)
139149

140-
if keys is not None and self.search_label is not None:
141-
assert self.search_label in keys, (
142-
f"The label '{self.search_label}' was not " f"available in {keys}" ""
143-
)
150+
super().render(**kwargs)

tests/test_folium.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -98,8 +98,8 @@ def test_init(self):
9898
assert self.m.width == (900, "px")
9999
assert self.m.left == (0, "%")
100100
assert self.m.top == (0, "%")
101-
assert self.m.no_touch is False
102-
assert self.m.disable_3d is False
101+
assert self.m.global_switches.no_touch is False
102+
assert self.m.global_switches.disable_3d is False
103103
assert self.m.font_size == "1.5rem"
104104
assert self.m.to_dict() == {
105105
"name": "Map",
@@ -465,29 +465,29 @@ def test_global_switches(self):
465465
out = m._parent.render()
466466
out_str = "".join(out.split())
467467
assert '"preferCanvas":true' in out_str
468-
assert not m.no_touch
469-
assert not m.disable_3d
468+
assert not m.global_switches.no_touch
469+
assert not m.global_switches.disable_3d
470470

471471
m = folium.Map(no_touch=True)
472472
out = m._parent.render()
473473
out_str = "".join(out.split())
474474
assert '"preferCanvas":false' in out_str
475-
assert m.no_touch
476-
assert not m.disable_3d
475+
assert m.global_switches.no_touch
476+
assert not m.global_switches.disable_3d
477477

478478
m = folium.Map(disable_3d=True)
479479
out = m._parent.render()
480480
out_str = "".join(out.split())
481481
assert '"preferCanvas":false' in out_str
482-
assert not m.no_touch
483-
assert m.disable_3d
482+
assert not m.global_switches.no_touch
483+
assert m.global_switches.disable_3d
484484

485485
m = folium.Map(prefer_canvas=True, no_touch=True, disable_3d=True)
486486
out = m._parent.render()
487487
out_str = "".join(out.split())
488488
assert '"preferCanvas":true' in out_str
489-
assert m.no_touch
490-
assert m.disable_3d
489+
assert m.global_switches.no_touch
490+
assert m.global_switches.disable_3d
491491

492492
def test_json_request(self):
493493
"""Test requests for remote GeoJSON files."""

tests/test_map.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -109,8 +109,7 @@ def test_popup_unicode():
109109
def test_popup_sticky():
110110
m = Map()
111111
popup = Popup("Some text.", sticky=True).add_to(m)
112-
script = popup._template.module.__dict__.get("script", None)
113-
rendered = script(this=popup, kwargs={})
112+
rendered = popup._template.render(this=popup, kwargs={})
114113
expected = """
115114
var {popup_name} = L.popup({{
116115
"maxWidth": "100%",
@@ -132,8 +131,7 @@ def test_popup_sticky():
132131
def test_popup_show():
133132
m = Map()
134133
popup = Popup("Some text.", show=True).add_to(m)
135-
script = popup._template.module.__dict__.get("script", None)
136-
rendered = script(this=popup, kwargs={})
134+
rendered = popup._template.render(this=popup, kwargs={})
137135
expected = """
138136
var {popup_name} = L.popup({{
139137
"maxWidth": "100%","autoClose": false,
@@ -153,8 +151,7 @@ def test_popup_show():
153151
def test_popup_backticks():
154152
m = Map()
155153
popup = Popup("back`tick`tick").add_to(m)
156-
script = popup._template.module.__dict__.get("script", None)
157-
rendered = script(this=popup, kwargs={})
154+
rendered = popup._template.render(this=popup, kwargs={})
158155
expected = """
159156
var {popup_name} = L.popup({{
160157
"maxWidth": "100%",
@@ -173,8 +170,7 @@ def test_popup_backticks():
173170
def test_popup_backticks_already_escaped():
174171
m = Map()
175172
popup = Popup("back\\`tick").add_to(m)
176-
script = popup._template.module.__dict__.get("script", None)
177-
rendered = script(this=popup, kwargs={})
173+
rendered = popup._template.render(this=popup, kwargs={})
178174
expected = """
179175
var {popup_name} = L.popup({{
180176
"maxWidth": "100%",

0 commit comments

Comments
 (0)