Prompted by a Stack Overflow question on whether there was a way to display Python code comments as formatted markdown followed by the code output, I came up with some really simple IPython magic –
innovationOUtside/fstring-magic – that will interpret code cell content as a simple formatted string or as an f-string and then display formatted markdown output.
My thinking is that this might be useful where a notebook or markdown file is being used to author a Jupyter Book generated HTML site and inline code outputs are required in text without having to use the currently recommended
glue package allows you to “add a key to variables in a notebook, then display those variables in markdown sections of a Jupyter Book by referencing the key. This is similar in style to the
nbextensions/python-markdown package which allows you to display the output value of code objects inline within markdown cells.
Using the f-string magic, we can author markdown that includes code object references similar to the glue or python-markdown approaches (or the use of inline code references in Rmd/bookdown, for example) and then render it via code cell outputs. In a Jupyter Book context, the code cell input can then be removed using a
remove-input tag so that only the output formatted markdown is displayed.
In terms of workflow, whilst it would be handy to be able to do this natively in Jupyter Book, we can imagine a hacky workflow to help automate this, as described in this issue, specifically, create a simple pipeline process to transform magicked cells according to something like the following recipe:
if cell.type=='md' and 'f-string` in tags: #convert cell type to 'code' # tag cell as `remove-input` # prefix code cell body with appropriate magic
One thought on “Displaying Jupyter Notebook Code Cell Content As Formatted Markdown/HTML Code Cell Output”
This is very cool! Did not know about some of these packages!
Comments are closed.