Underneath, Jupyter notebooks are json files that holds content for code cells, markdown cells and corresponding output. Given this, it is possible to load a notebook file as json and attempt to generate html elements based on its content.
While this approach offers quite a bit of control, it is also effortful as you will need to fully understand the Jupyter json structure and also implement layout/styling (e.g., how to style code cells, output cells, parse & render markdown cells, code syntax highlighting, table formatting where applicable etc.). It is a lot of work! And perhaps unnecessary work.
The approach I used primarily relies on nbconvert
. nbconvert is a Python package that converts Jupyter Notebooks to multiple target formats including HTML, Markdown, LaTeX, ReStructuredText and other formats. It provides default templates that govern the visual layout and style for each of these target formats. Results from nbconvert (which are already styled) are consequently easier to include in a web application.
I initially explored the markdown format as my Gatsby application already had a blog section based on remarkdown (a format that that allows writing JSX inside markdown files). However, I found that the markdown format generated by nbconvert were not immediately compatible with Gatsby causing parse errors. In theory, you can write a custom template to govern the generation of markdown files using the nbconvert templating system; however, again this route felt like unnecessary work.
I ended up using the following
nbconvert to convert the notebook to
- Wrote some custom
css styling to format cells and output; add custom
- Wrote a script in
gastsby-node.js to automatically convert all notebooks in a directory to
html and copy to the Gatsby static folder
- Wrote a React component to load these html files and render them in iframes.
Given that I have some experience with css and html, I found it easier to focus my effort on writing css rules to style/control the notebook as opposed to rendering other formats like markdown, latex etc.