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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: add html_head_file to inject custom head scripts into the app (#2926)
Myles Scolnick12c3a1112cd6
diff --git a/docs/guides/configuration/html_head.md b/docs/guides/configuration/html_head.mdnew file mode 100644index 0000000000..b806eae5a1--- /dev/null+++ b/docs/guides/configuration/html_head.md@@ -0,0 +1,64 @@+# Custom HTML Head++You can include a custom HTML head file to add additional functionality to your notebook, such as analytics, custom fonts, meta tags, or external scripts. The contents of this file will be injected into the `<head>` section of your notebook.++To include a custom HTML head file, specify the relative file path in your app configuration. This can be done through the marimo editor UI in the notebook settings (top-right corner).++This will be reflected in your notebook file:++```python+app = marimo.App(html_head_file="head.html")+```++## Example Use Cases++Here are some common use cases for custom HTML head content:++1. **Google Analytics**++```html+<!-- head.html -->+<!-- Google tag (gtag.js) -->+<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>+<script>+ window.dataLayer = window.dataLayer || [];+ function gtag() {+ dataLayer.push(arguments);+ }+ gtag('js', new Date());+ gtag('config', 'G-XXXXXXXXXX');+</script>+```++2. **Custom Fonts**++```html+<!-- head.html -->+<link rel="preconnect" href="https://fonts.googleapis.com" />+<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />+<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet" />+```++3. **Meta Tags**++```html+<!-- head.html -->+<meta name="description" content="My marimo notebook" />+<meta name="keywords" content="data science, visualization, python" />+<meta name="author" content="Your Name" />+<meta property="og:title" content="My Notebook" />+<meta property="og:description" content="Interactive data analysis with marimo" />+<meta property="og:image" content="https://example.com/thumbnail.jpg" />+```++4. **External Scripts and Libraries**++```html+<!-- head.html -->+<!-- Load external JavaScript libraries -->+<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>+<script src="https://cdn.jsdelivr.net/npm/d3@7"></script>++<!-- Load external CSS -->+<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" />+```diff --git a/docs/guides/configuration/index.md b/docs/guides/configuration/index.mdindex bf477a167f..95c30aa8ab 100644--- a/docs/guides/configuration/index.md+++ b/docs/guides/configuration/index.md@@ -7,6 +7,7 @@runtime_configurationtheming+ html_head```marimo offers two types of configuration: User Configuration and App@@ -21,7 +22,8 @@ App Configuration is specific to each notebook and is stored in the `notebook.py- Notebook width- Notebook title-- [Custom CSS](/guides/configuration/theming)+- [Custom CSS](/guides/configuration/theming.md)+- [Custom HTML Head](/guides/configuration/html_head.md)- Automatically download HTML snapshotsConfigure these settings through the notebook menu.diff --git a/docs/guides/configuration/theming.md b/docs/guides/configuration/theming.mdindex ba6ba8e486..7d39b8690e 100644--- a/docs/guides/configuration/theming.md+++ b/docs/guides/configuration/theming.md@@ -43,11 +43,18 @@ Here is an example of a custom CSS file that changes the font of the notebook:}```+## Custom HTML Head++You can further customize your notebook by adding custom HTML in the `<head>` section of your notebook. This allows you to add additional functionality to your notebook, such as analytics, custom fonts, meta tags, or external scripts.++See the [Custom HTML Head](/guides/configuration/html_head.md) guide for more details.+## Community ThemesThe marimo community maintains a [library of custom themes](https://github.com/metaboulie/marimo-themes) that you can use in your notebooks. The library includes various themes like "coldme", "nord", "mininini", and "wigwam", each supporting both light and dark modes.You can:+- Browse and download existing themes- Use them in your own notebooks- Contribute your own themes to share with the community@@ -56,4 +63,4 @@ Visit the [marimo-themes repository](https://github.com/metaboulie/marimo-themes## More customizations-We want to hear from you! If you have any suggestions for more theming options, please let us know on [GitHub](https://github.com/marimo-team/marimo/discussions)+We want to hear from you! If you have any suggestions for more customization options, please let us know on [GitHub](https://github.com/marimo-team/marimo/discussions)diff --git a/frontend/src/components/app-config/app-config-form.tsx b/frontend/src/components/app-config/app-config-form.tsxindex 46a2ffca6c..9ac67e3516 100644--- a/frontend/src/components/app-config/app-config-form.tsx+++ b/frontend/src/components/app-config/app-config-form.tsx@@ -146,6 +146,34 @@ export const AppConfigForm: React.FC = () => {</div>)}/>+ <FormField+ control={form.control}+ name="html_head_file"+ render={({ field }) => (+ <div className="flex flex-col gap-y-1">+ <FormItem className="flex flex-row items-center space-x-1 space-y-0">+ <FormLabel className="flex-shrink-0">HTML Head</FormLabel>+ <FormControl>+ <Input+ {...field}+ value={field.value ?? ""}+ placeholder="head.html"+ onChange={(e) => {+ field.onChange(e.target.value);+ }}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ <FormDescription>+ A filepath to an HTML file to be injected into the{" "}+ <Kbd className="inline">{"<head/>"}</Kbd> section of the+ notebook. Use this to add analytics, custom fonts, meta tags, or+ external scripts.+ </FormDescription>+ </div>+ )}+ /><FormFieldcontrol={form.control}name="auto_download"diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.tsindex 5a43382990..82dd4f11d4 100644--- a/frontend/src/core/config/config-schema.ts+++ b/frontend/src/core/config/config-schema.ts@@ -167,6 +167,7 @@ export const AppConfigSchema = z}),app_title: AppTitleSchema.nullish(),css_file: z.string().nullish(),+ html_head_file: z.string().nullish(),auto_download: z.array(z.string()).default([]),}).default({ width: "medium", auto_download: [] });diff --git a/marimo/_ast/app.py b/marimo/_ast/app.pyindex affdae4c08..046871a6ca 100644--- a/marimo/_ast/app.py+++ b/marimo/_ast/app.py@@ -71,6 +71,9 @@ class _AppConfig:# CSS file, relative to the app filecss_file: Optional[str] = None+ # HTML head file, relative to the app file+ html_head_file: Optional[str] = None+# Whether to automatically download the app as HTML and Markdownauto_download: List[Literal["html", "markdown"]] = field(default_factory=listdiff --git a/marimo/_server/file_manager.py b/marimo/_server/file_manager.pyindex 61ceee281f..ac47ea2278 100644--- a/marimo/_server/file_manager.py+++ b/marimo/_server/file_manager.py@@ -202,6 +202,12 @@ class AppFileManager:return Nonereturn read_css_file(css_file, self.filename)+ def read_html_head_file(self) -> Optional[str]:+ html_head_file = self.app.config.html_head_file+ if not html_head_file or not self.filename:+ return None+ return read_html_head_file(html_head_file, self.filename)+@propertydef path(self) -> Optional[str]:if self.filename is None:@@ -326,3 +332,26 @@ def read_css_file(css_file: str, filename: Optional[str]) -> Optional[str]:str(e),)return None+++def read_html_head_file(+ html_head_file: str, filename: Optional[str]+) -> Optional[str]:+ if not html_head_file or not filename:+ return None++ app_dir = os.path.dirname(filename)+ filepath = os.path.join(app_dir, html_head_file)+ if not os.path.exists(filepath):+ LOGGER.error("HTML head file %s does not exist", html_head_file)+ return None+ try:+ with open(filepath) as f:+ return f.read()+ except OSError as e:+ LOGGER.warning(+ "Failed to open HTML head file %s for reading: %s",+ filepath,+ str(e),+ )+ return Nonediff --git a/marimo/_server/templates/templates.py b/marimo/_server/templates/templates.pyindex 685b791a99..cc7951913e 100644--- a/marimo/_server/templates/templates.py+++ b/marimo/_server/templates/templates.py@@ -14,7 +14,7 @@ from marimo._config.config import MarimoConfigfrom marimo._messaging.cell_output import CellOutputfrom marimo._output.utils import uri_encode_componentfrom marimo._server.api.utils import parse_title-from marimo._server.file_manager import read_css_file+from marimo._server.file_manager import read_css_file, read_html_head_filefrom marimo._server.model import SessionModefrom marimo._server.tokens import SkewProtectionToken@@ -74,6 +74,15 @@ def notebook_page_template(# Append to headhtml = html.replace("</head>", f"{css_contents}</head>")+ # Add HTML head file contents if specified+ if app_config.html_head_file:+ head_contents = read_html_head_file(+ app_config.html_head_file, filename=filename+ )+ if head_contents:+ # Append to head+ html = html.replace("</head>", f"{head_contents}</head>")+return html@@ -151,6 +160,16 @@ def static_notebook_template(</script>""")+ # Add HTML head file contents if specified+ if app_config.html_head_file:+ head_contents = read_html_head_file(+ app_config.html_head_file, filename=filepath+ )+ if head_contents:+ static_block += dedent(f"""+ {head_contents}+ """)+# If has custom css, inline the css and add to the headif app_config.css_file:css_contents = read_css_file(app_config.css_file, filename=filepath)diff --git a/marimo/_smoke_tests/theming/custom_head.py b/marimo/_smoke_tests/theming/custom_head.pynew file mode 100644index 0000000000..b0581b4a69--- /dev/null+++ b/marimo/_smoke_tests/theming/custom_head.py@@ -0,0 +1,53 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "vega-datasets",+# "marimo",+# ]+# ///++import marimo++__generated_with = "0.9.21"+app = marimo.App(width="medium", html_head_file="head.html")+++def __():+ import marimo as mo+ from vega_datasets import data+ return data, mo+++def __(data):+ data.cars()+ return+++def __(mo):+ mo.callout(+ mo.md("""+ ## Callout++ This font should be styled+ """)+ )+ return+++def __(mo):+ mo.md(+ r"""+ # heading++ Here is a paragraph+ """+ )+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_smoke_tests/theming/head.html b/marimo/_smoke_tests/theming/head.htmlnew file mode 100644index 0000000000..9201370524--- /dev/null+++ b/marimo/_smoke_tests/theming/head.html@@ -0,0 +1,16 @@+<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:300,300italic,800,800italic" />+<style>+ :root {+ --marimo-text-font: 'Montserrat', sans-serif;+ --marimo-heading-font: 'Montserrat', sans-serif;+ }++ .paragraph {+ font-size: 1.2rem;+ color: light-dark(navy, pink);+ }++ h1 {+ color: light-dark(red, blue) !important;+ }+</style>diff --git a/openapi/api.yaml b/openapi/api.yamlindex d1282541bf..1c82b47c5c 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -888,6 +888,9 @@ components:css_file:nullable: truetype: string+ html_head_file:+ nullable: true+ type: stringlayout_file:nullable: truetype: string@@ -1913,7 +1916,7 @@ components:type: objectinfo:title: marimo API- version: 0.9.17+ version: 0.9.21openapi: 3.1.0paths:/@file/{filename_and_length}:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex 67e855b05b..eae5cb6d9d 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -2358,6 +2358,7 @@ export interface components {app_title?: string | null;auto_download: ("html" | "markdown")[];css_file?: string | null;+ html_head_file?: string | null;layout_file?: string | null;/** @enum {string} */width: "normal" | "compact" | "medium" | "full";diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.pyindex 0203972b22..f52502cc22 100644--- a/tests/_ast/test_app.py+++ b/tests/_ast/test_app.py@@ -307,6 +307,7 @@ class TestApp:assert app._config.asdict() == {"app_title": None,"css_file": None,+ "html_head_file": None,"width": "full","layout_file": None,"auto_download": [],@@ -515,6 +516,7 @@ def test_app_config() -> None:assert config.asdict() == {"app_title": None,"css_file": None,+ "html_head_file": None,"width": "full","layout_file": None,"auto_download": [],@@ -530,6 +532,7 @@ def test_app_config_extra_args_ignored() -> None:assert config.asdict() == {"app_title": None,"css_file": None,+ "html_head_file": None,"width": "full","layout_file": None,"auto_download": [],diff --git a/tests/_ast/test_app_config.py b/tests/_ast/test_app_config.pyindex 24f9fcce6a..03326f81d3 100644--- a/tests/_ast/test_app_config.py+++ b/tests/_ast/test_app_config.py@@ -12,6 +12,7 @@ def test_app_config_default():assert config.width == "compact"assert config.app_title is Noneassert config.css_file is None+ assert config.html_head_file is Noneassert config.auto_download == []@@ -20,6 +21,7 @@ def test_app_config_from_untrusted_dict():"width": "full","app_title": "My App","css_file": "custom.css",+ "html_head_file": "head.html","auto_download": ["html", "markdown"],"invalid_key": "should be ignored",}@@ -27,6 +29,7 @@ def test_app_config_from_untrusted_dict():assert config.width == "full"assert config.app_title == "My App"assert config.css_file == "custom.css"+ assert config.html_head_file == "head.html"assert config.auto_download == ["html", "markdown"]assert not hasattr(config, "invalid_key")@@ -36,6 +39,7 @@ def test_app_config_asdict():width="medium",app_title="Test App",css_file="style.css",+ html_head_file="head.html",auto_download=["html"],)config_dict = config.asdict()@@ -43,6 +47,7 @@ def test_app_config_asdict():"width": "medium","app_title": "Test App","css_file": "style.css",+ "html_head_file": "head.html","auto_download": ["html"],"layout_file": None,}diff --git a/tests/_server/templates/snapshots/export5.txt b/tests/_server/templates/snapshots/export5.txtnew file mode 100644index 0000000000..359306edd4--- /dev/null+++ b/tests/_server/templates/snapshots/export5.txt@@ -0,0 +1,91 @@+<!DOCTYPE html>+<html lang="en">+ <head>+ <base href='/' />+ <meta charset="utf-8" />+ <link rel="icon" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/favicon.ico" />+ <!-- Preload is necessary because we show these images when we disconnect from the server,+ but at that point we cannot load these images from the server -->+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/gradient.png"" as="image" />+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/noise.png"" as="image" />+ <!-- Preload the fonts -->+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/Lora-VariableFont_wght.ttf"" as="font" crossorigin="anonymous" />+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/PTSans-Regular.ttf"" as="font" crossorigin="anonymous" />+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/PTSans-Bold.ttf"" as="font" crossorigin="anonymous" />+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/FiraMono-Regular.ttf"" as="font" crossorigin="anonymous" />+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/FiraMono-Medium.ttf"" as="font" crossorigin="anonymous" />+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/FiraMono-Bold.ttf"" as="font" crossorigin="anonymous" />++ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <meta name="theme-color" content="#000000" />+ <meta name="description" content="a marimo app" />+ <link rel="apple-touch-icon" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/apple-touch-icon.png" />+ <link rel="manifest" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/manifest.json" />++ <script data-marimo="true">+ function __resizeIframe(obj) {+ var scrollbarHeight = 20; // Max between windows, mac, and linux++ function setHeight() {+ var element = obj.contentWindow.document.documentElement;+ // If there is no vertical scrollbar, we don't need to resize the iframe+ if (element.scrollHeight === element.clientHeight) {+ return;+ }++ // Create a new height that includes the scrollbar height if it's visible+ var hasHorizontalScrollbar = element.scrollWidth > element.clientWidth;+ var newHeight = element.scrollHeight + (hasHorizontalScrollbar ? scrollbarHeight : 0);++ // Only update the height if it's different from the current height+ if (obj.style.height !== `${newHeight}px`) {+ obj.style.height = `${newHeight}px`;+ }+ }++ // Resize the iframe to the height of the content and bottom scrollbar height+ setHeight();++ // Resize the iframe when the content changes+ const resizeObserver = new ResizeObserver((entries) => {+ setHeight();+ });+ resizeObserver.observe(obj.contentWindow.document.body);+ }+ </script>+ <marimo-filename hidden>notebook.py</marimo-filename>+ <marimo-mode data-mode='read' hidden></marimo-mode>+ <marimo-version data-version='0.0.0' hidden></marimo-version>+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "package_management": {"manager": "pip"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}}' hidden></marimo-user-config>+ <marimo-app-config data-config='{"html_head_file": "head.html", "width": "compact"}' hidden></marimo-app-config>+ <marimo-server-token data-token='token' hidden></marimo-server-token>+ <title>notebook</title>+ <script type="module" crossorigin crossorigin="anonymous" src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.js""></script>+ <link rel="stylesheet" crossorigin crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.css"">++<script data-marimo="true">+ window.__MARIMO_STATIC__ = {};+ window.__MARIMO_STATIC__.version = "0.0.0";+ window.__MARIMO_STATIC__.notebookState = {"cellIds": [], "cellNames": [], "cellCodes": [], "cellConfigs": [], "cellOutputs": {}, "cellConsoleOutputs": {}};+ window.__MARIMO_STATIC__.assetUrl = "https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist";+ window.__MARIMO_STATIC__.files = {};+</script>+++<!-- Google tag (gtag.js) -->+<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>+<script>+ window.dataLayer = window.dataLayer || [];+ function gtag(){dataLayer.push(arguments);}+ gtag('js', new Date());+ gtag('config', 'G-XXXXXXXXXX');+</script>+<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">++</head>+ <body>+ <div id="root"></div>+ <marimo-code hidden=""></marimo-code>+<marimo-code-hash hidden="">2b33215fadf3c54926d5c4100348afc158dbff4c94b15044e3a7fe804f80ed2d</marimo-code-hash>+</body>+</html>diff --git a/tests/_server/templates/test_templates.py b/tests/_server/templates/test_templates.pyindex 7b748e4b0f..0b700e178c 100644--- a/tests/_server/templates/test_templates.py+++ b/tests/_server/templates/test_templates.py@@ -105,6 +105,39 @@ class TestNotebookPageTemplate(unittest.TestCase):finally:os.remove(css_file)+ def test_notebook_page_template_custom_head(self) -> None:+ # Create html head file+ head = """+ <!-- Google tag (gtag.js) -->+ <script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>+ <script>+ window.dataLayer = window.dataLayer || [];+ function gtag(){dataLayer.push(arguments);}+ gtag('js', new Date());+ gtag('config', 'G-XXXXXXXXXX');+ </script>+ <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">+ """++ head_file = os.path.join(os.path.dirname(self.filename), "head.html")+ with open(head_file, "w") as f:+ f.write(head)++ try:+ result = templates.notebook_page_template(+ self.html,+ self.base_url,+ self.user_config,+ self.server_token,+ _AppConfig(html_head_file="head.html"),+ self.filename,+ self.mode,+ )++ assert head in result+ finally:+ os.remove(head_file)+class TestHomePageTemplate(unittest.TestCase):def setUp(self) -> None:@@ -271,3 +304,43 @@ class TestStaticNotebookTemplate(unittest.TestCase):snapshot("export4.txt", normalize_index_html(result))finally:os.remove(css_file)++ def test_static_notebook_template_with_head(self) -> None:+ # Create html head file+ head = """+ <!-- Google tag (gtag.js) -->+ <script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>+ <script>+ window.dataLayer = window.dataLayer || [];+ function gtag(){dataLayer.push(arguments);}+ gtag('js', new Date());+ gtag('config', 'G-XXXXXXXXXX');+ </script>+ <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">+ """++ head_file = os.path.join(os.path.dirname(self.filename), "head.html")+ with open(head_file, "w") as f:+ f.write(head)++ try:+ result = templates.static_notebook_template(+ self.html,+ self.user_config,+ self.server_token,+ _AppConfig(html_head_file="head.html"),+ self.filename,+ "",+ hash_code(self.code),+ [],+ [],+ [],+ [],+ {},+ {},+ {},+ )++ snapshot("export5.txt", normalize_index_html(result))+ finally:+ os.remove(head_file)