File tree Expand file tree Collapse file tree 2 files changed +18
-1
lines changed Expand file tree Collapse file tree 2 files changed +18
-1
lines changed Original file line number Diff line number Diff line change @@ -202,6 +202,7 @@ as the first non-empty line under
202202the section header for an examples section will prevent a directive from being inserted,
203203allowing 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
206207The 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
213214try_examples_global_button_text = " Try it in your browser!"
214215try_examples_global_height = " 200px"
215216try_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
218224There is no option to set a global specific height because the proper height
Original file line number Diff line number Diff line change 2222from sphinx .util .fileutil import copy_asset
2323from 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
2731import jupytext
2832import 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)
You can’t perform that action at this time.
0 commit comments