How to display jupyter notebooks on your hugo blog

⋅ 2 minute read


I like the simplicity and ease of use of the Hugo, the static site generator that powers this blog. However, as a data scientist I want to be able to make an argument using code, data, and graphs in a Jupyter notebook. This post explains my setup how to convert a Jupyter notebook into a blog post for this website, such as this . Before I started, my requirements were:

  • I wanted to be able to easily share both the original notebook (and accompanying data) as well as the website version.
  • I wanted to regenerate the website version from the notebook file with at most one command and without any post-processing. This is important because I usually work iteratively on notebooks.

Writing the notebook

The source code for this blog is available in this Gitlab repository (link) . I created a new top-level folder notebooks/ and a subfolder for each notebook project I want to post about. This allows me to easily link to the Jupyter notebook and data to make it reproducible.

It is important that you start the notebook with a cell that contains the front matter of the blog post, e.g.

# My notebook title

Date: 2018-06-01  
Author: firstname lastname  
Categories: category1, category2  
Tags: tag1, tag2, tag3  
<!--eofm-->

The <!--eofm--> is important to divide the front matter from the rest of the notebook.

Converting to markdown

To align with the markdown-based workflow of Hugo we need to convert the notebook to markdown. The script nb2hugo (link) does exactly that. We can install it for example via: pip install nb2hugo.

To convert the notebook to markdown we navigate into the notebook folder and run

nb2hugo covid_bipartisan_bayesian.ipynb --site-dir /Users/rob/hugoblog/ --section posts

This command writes the output markdown file covid_bipartisan_bayesian.md into the specified folder posts/.

Adjusting the website CSS

I made two more adjustment to the style of this blog to better display the “markdown-ified” notebook. Both pandas code and displayed dataframes are quite wide so I:

  • increased the content width slightly to 800px,
  • decreased the font-size for the text in the code cells to 0.75rem.

While still not perfect, I think this gives a decent result.


If you have any thoughts, questions, or feedback about this post, I would love to hear it. Please reach out to me via email.

Tags:
#hugo   #notebook  

Related: