Skip to content

Commit ec87296

Browse files
KhadeerBasha1232claudehansthen
authored
Add template parameters to JsCode (#2333)
JsCode now accepts keyword arguments that fill %(name)s placeholders. Elements are replaced by their Javascript variable name, JsCode objects by their code, and other values are formatted as usual. Placeholders are filled in at render time; code without parameters is used as is. Closes #2121 Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Hans Then <hans.then@gmail.com>
1 parent ba0708b commit ec87296

3 files changed

Lines changed: 122 additions & 4 deletions

File tree

‎docs/advanced_guide/customize_javascript_and_css.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,3 +77,22 @@ rt.add_js_link("dayjs", "https://cdn.jsdelivr.net/npm/dayjs@1.11.10/dayjs.min.js
7777
rt.add_to(m)
7878
m
7979
```
80+
81+
## Referring to other map objects in JsCode
82+
Inside a `JsCode` block you often need the Javascript variable of another folium object, such as a marker or a layer. You can write `%(name)s` placeholders in the code and pass the objects as keyword arguments. Folium objects are replaced by their Javascript variable name when the map is rendered, other `JsCode` objects by their code, and any other value is inserted as is.
83+
84+
When you pass parameters, write a literal `%` in the code as `%%`.
85+
86+
```{code-cell} ipython3
87+
from folium.utilities import JsCode
88+
89+
m = folium.Map(location=[45, -30], zoom_start=4)
90+
marker = folium.Marker([45, -30], popup="Hello!").add_to(m)
91+
92+
m.on(click=JsCode("""
93+
function(e) {
94+
%(marker)s.setLatLng(e.latlng).openPopup();
95+
}
96+
""", marker=marker))
97+
m
98+
```

‎folium/utilities.py‎

Lines changed: 54 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -428,13 +428,63 @@ def get_and_assert_figure_root(obj: Element) -> Figure:
428428

429429

430430
class JsCode:
431-
"""Wrapper around Javascript code."""
431+
"""Wrapper around Javascript code.
432432
433-
def __init__(self, js_code: "str | JsCode"):
433+
Parameters
434+
----------
435+
js_code: str or JsCode
436+
The Javascript code. It may contain ``%(name)s`` placeholders that are
437+
filled in with the keyword arguments.
438+
**params:
439+
Values for the placeholders in `js_code`. A folium (or branca) element
440+
is replaced by its Javascript variable name, a JsCode object by its
441+
code, and any other value is formatted with the ``%`` operator.
442+
The placeholders are filled in when the code is rendered.
443+
444+
When parameters are given, a literal ``%`` in the code must be written as
445+
``%%``. Without parameters the code is used as is.
446+
447+
Examples
448+
--------
449+
>>> m = folium.Map()
450+
>>> marker = folium.Marker([45, -30]).add_to(m)
451+
>>> handler = JsCode(
452+
... '''
453+
... function(e) {
454+
... %(marker)s.openPopup();
455+
... }
456+
... ''',
457+
... marker=marker,
458+
... )
459+
"""
460+
461+
def __init__(self, js_code: "str | JsCode", **params: Any):
434462
if isinstance(js_code, JsCode):
435-
self.js_code: str = js_code.js_code
463+
self._template: str = js_code._template
464+
self.params: dict[str, Any] = {**js_code.params, **params}
436465
else:
437-
self.js_code = js_code
466+
self._template = js_code
467+
self.params = params
468+
469+
@property
470+
def js_code(self) -> str:
471+
if not self.params:
472+
return self._template
473+
return self._template % {
474+
key: self._resolve(value) for key, value in self.params.items()
475+
}
476+
477+
@js_code.setter
478+
def js_code(self, value: str) -> None:
479+
self._template = value
480+
481+
@staticmethod
482+
def _resolve(value: Any) -> Any:
483+
if isinstance(value, JsCode):
484+
return value.js_code
485+
if isinstance(value, Element):
486+
return value.get_name()
487+
return value
438488

439489
def __str__(self):
440490
return self.js_code

‎tests/test_utilities.py‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,55 @@ def test_js_code_init_js_code():
272272
assert isinstance(js_code_2.js_code, str)
273273

274274

275+
def test_js_code_without_params_is_not_formatted():
276+
js_code = JsCode("var x = 10 % 3; var y = '%(name)s';")
277+
assert js_code.js_code == "var x = 10 % 3; var y = '%(name)s';"
278+
279+
280+
def test_js_code_params_element():
281+
m = Map()
282+
marker = Marker([0, 0]).add_to(m)
283+
js_code = JsCode("%(marker)s.openPopup();", marker=marker)
284+
assert js_code.js_code == f"{marker.get_name()}.openPopup();"
285+
assert str(js_code) == js_code.js_code
286+
287+
288+
def test_js_code_params_js_code_and_plain_values():
289+
inner = JsCode("function(e) { return %(n)s; }", n=5)
290+
js_code = JsCode(
291+
"var f = %(func)s; var s = '%(text)s'; var p = 10 %% 3;",
292+
func=inner,
293+
text="hello",
294+
)
295+
assert js_code.js_code == (
296+
"var f = function(e) { return 5; }; var s = 'hello'; var p = 10 % 3;"
297+
)
298+
299+
300+
def test_js_code_params_merged_when_wrapping_js_code():
301+
js_code = JsCode("%(a)s %(b)s", a=1, b=2)
302+
js_code_2 = JsCode(js_code, b=3)
303+
assert js_code_2.js_code == "1 3"
304+
assert js_code.js_code == "1 2"
305+
306+
307+
def test_js_code_params_resolved_at_render_time():
308+
m = Map()
309+
marker = Marker([0, 0])
310+
js_code = JsCode("%(marker)s", marker=marker)
311+
marker._name = "SomethingElse"
312+
marker.add_to(m)
313+
assert js_code.js_code == marker.get_name()
314+
315+
316+
def test_js_code_params_rendered_in_map():
317+
m = Map()
318+
marker = Marker([0, 0]).add_to(m)
319+
m.on(click=JsCode("function(e) { %(marker)s.openPopup(); }", marker=marker))
320+
html = m.get_root().render()
321+
assert f"{marker.get_name()}.openPopup();" in html
322+
323+
275324
@pytest.mark.parametrize(
276325
"value,expected",
277326
[

0 commit comments

Comments
 (0)