How to convert a Jupyter Notebook to a page on this site

import time
from conv_modularized import convert

(Note: This is a sample output page from the process described within itself. The IPython notebook from which this originates can be found at https://benrosenberg.info/posts/convert_ipynb_to_page.ipynb, while the conv_modularized file is a simple rearrangement of the file described in a previous post about minimal IPYNB conversion. This rearranged version can be found here: https://benrosenberg.info/posts/conv_modularized.py.)

This notebook contains the steps to convert an IPython notebook (similar to this one) to an HTML file suitable for use on this site.

Start by putting in an input filename and title. Might want to leave the output filename as is though, as changing it to index.html could mean overwriting the index.html file in this directory.

IN_FILENAME = 'convert_ipynb_to_page.ipynb'
OUT_FILENAME = 'generated_{}.html'.format(time.time())
TITLE = 'Converting a IPYNB file to a page on this site'

TEMPLATE_FILENAME = 'converted_ipynb_template.html'

Now we can run the converter script and wrap the results in the required header and footer.

out_contents = convert(IN_FILENAME, standalone=False)

with open(TEMPLATE_FILENAME, 'r') as f:
    template_contents = f.read()

with open(OUT_FILENAME, 'w') as f:
    # 'IPYNB-CONTENT-GOES-HERE' is not a placeholder to fill in, it's a marker in the HTML template
    f.write(
        template_contents
            .replace('IPYNB-CONTENT-GOES-HERE', out_contents)
            .replace('TITLE-GOES-HERE', TITLE)
    )

At this point we can check the output file with a browser and make sure it looks good.

From here the next steps are to:

  • Create a subdirectory within /posts/ (e.g., /posts/mynewpost/)
  • Move the generated output file to this newly created directory
  • Rename this file to index.html
  • Create a link to this new index.html file in the /posts/index.html file so that it is accessible