Skip to content

Commit 662f3f7

Browse files
authored
allow adding a preamble for try_examples (#293)
* optionally allow adding a preamble * import `new_code_cell` * run `black` * use a configuration option of type `str` instead * document the new setting
1 parent b975ed7 commit 662f3f7

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

docs/directives/try_examples.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,7 @@ as the first non-empty line under
202202
the section header for an examples section will prevent a directive from being inserted,
203203
allowing for specification of examples sections which should not be made interactive.
204204

205+
A code cell containing common setup code (similar to `pytest`'s `doctest_namespace`) can be added using `try_examples_preamble`.
205206

206207
The button text, theme, and warning text can be set globally with the config variables
207208
`try_examples_global_button_text`, `try_examples_global_theme`, and `try_examples_global_warning_text` in `conf.py`;
@@ -213,6 +214,11 @@ global_enable_try_examples = True
213214
try_examples_global_button_text = "Try it in your browser!"
214215
try_examples_global_height = "200px"
215216
try_examples_global_warning_text = "Interactive examples are experimental and may not always work as expected."
217+
try_examples_preamble = """
218+
import datetime as dt
219+
220+
now = dt.datetime.now()
221+
"""
216222
```
217223

218224
There is no option to set a global specific height because the proper height

jupyterlite_sphinx/jupyterlite_sphinx.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,11 @@
2222
from sphinx.util.fileutil import copy_asset
2323
from sphinx.parsers import RSTParser
2424

25-
from ._try_examples import examples_to_notebook, insert_try_examples_directive
25+
from ._try_examples import (
26+
examples_to_notebook,
27+
insert_try_examples_directive,
28+
new_code_cell,
29+
)
2630

2731
import jupytext
2832
import nbformat
@@ -823,6 +827,12 @@ def run(self):
823827

824828
if notebook_unique_name is None:
825829
nb = examples_to_notebook(self.content, warning_text=warning_text)
830+
831+
preamble = self.env.config.try_examples_preamble
832+
if preamble:
833+
# insert after the "experimental" warning
834+
nb.cells.insert(1, new_code_cell(preamble))
835+
826836
self.content = None
827837
notebooks_dir = Path(self.env.app.srcdir) / CONTENT_DIR
828838
notebook_unique_name = f"{uuid4()}.ipynb".replace("-", "_")
@@ -1151,6 +1161,7 @@ def setup(app):
11511161
default=None,
11521162
rebuild="html",
11531163
)
1164+
app.add_config_value("try_examples_preamble", default=None, rebuild="html")
11541165

11551166
# Allow customising the button text for each directive (this is useful
11561167
# only when "new_tab" is set to True)

0 commit comments

Comments
 (0)