Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat(image): add caption support to mo.image (#2817)

eugene10ab926b1a35
diff --git a/marimo/_output/builder.py b/marimo/_output/builder.py
index cf5307c8f9..6ac965a322 100644
--- a/marimo/_output/builder.py
+++ b/marimo/_output/builder.py
@@ -149,6 +149,44 @@ class _HTMLBuilder:
f"<{component_name} {_join_params(params)}></{component_name}>"
)
+ @staticmethod
+ def figure(
+ children: Union[str, List[str]], *, style: Optional[str] = None
+ ) -> str:
+ resolved_children = (
+ [children] if isinstance(children, str) else children
+ )
+
+ params: List[Tuple[str, Union[str, None]]] = []
+ if style:
+ params.append(("style", style))
+
+ children_html = "".join(resolved_children)
+
+ if len(params) == 0:
+ return f"<figure>{children_html}</figure>"
+ else:
+ return f"<figure {_join_params(params)}>{children_html}</figure>"
+
+ @staticmethod
+ def figcaption(
+ children: Union[str, List[str]], *, style: Optional[str] = None
+ ) -> str:
+ resolved_children = (
+ [children] if isinstance(children, str) else children
+ )
+
+ params: List[Tuple[str, Union[str, None]]] = []
+ if style:
+ params.append(("style", style))
+
+ children_html = "".join(resolved_children)
+
+ if len(params) == 0:
+ return f"<figcaption>{children_html}</figcaption>"
+ else:
+ return f"<figcaption {_join_params(params)}>{children_html}</figcaption>"
+
def _join_params(params: List[Tuple[str, Union[str, None]]]) -> str:
# Filter None
diff --git a/marimo/_plugins/stateless/image.py b/marimo/_plugins/stateless/image.py
index 9b5a285119..d0f98384a0 100644
--- a/marimo/_plugins/stateless/image.py
+++ b/marimo/_plugins/stateless/image.py
@@ -93,6 +93,7 @@ def image(
height: Optional[int] = None,
rounded: bool = False,
style: Optional[dict[str, Any]] = None,
+ caption: Optional[str] = None,
) -> Html:
"""Render an image as HTML.
@@ -111,6 +112,7 @@ def image(
width=100,
height=100,
rounded=True,
+ caption="Marimo logo",
)
```
@@ -123,6 +125,7 @@ def image(
- `height`: the height of the image in pixels
- `rounded`: whether to round the corners of the image
- `style`: a dictionary of CSS styles to apply to the image
+ - `caption`: the caption of the image
**Returns.**
@@ -158,4 +161,18 @@ def image(
}
)
img = h.img(src=resolved_src, alt=alt, style=styles)
+ if caption is not None:
+ return Html(
+ h.figure(
+ [
+ img,
+ h.figcaption(
+ [caption],
+ style="color: var(--muted-foreground); "
+ "text-align: center; margin-top: 0.5rem;",
+ ),
+ ],
+ style="display: flex; flex-direction: column;",
+ )
+ )
return Html(img)