Embedding jupyter notebooks as jekyll blog posts

Jupyter notebook is now a paradigm approach to present and communicate scientific results, as it promotes the readibility and enriches the code by markdown text and colored figures. It is then appealing to create blog posts directly from Jupyter notebooks to present the calcultation results without worrying about how to convert notebooks into the formats for publication. People usually do it by two steps:

  1. Export the notebook as a html file.
  2. Copy the content between <html></html> tags and paste them into a markdown post file .md

Then you are done! It’s as simple as that. However, you may find the notebook appearance is messed up with the global style setting. To resolve this, we need to create an additional post-jupyter.html file in the _layouts folder with the following pattern (see my github for example):

<div class="post">
  <div class="post-jupyter">
    { post content }
  </div>
</div>

and add the corresponding styles in .scss:

.post {
  .post-jupyter {
    // reset the paragraph back to global style
    font-family: global-font-family;
    pre {
      .nc {
        text-decoration: none;
      }
    }
    // fix conflicts between global and local styles
    .jp-Cell-inputWrapper pre {
      border-radius: 0;
      background-color: var(--jp-cell-editor-background);
      .nn {
        text-decoration: none;
      }
    }
    .jp-Cell-outputWrapper pre {
      background-color: var(--global-bg-color);
    }
  }
}

We also need to add light theme and dark theme css files in _sass folder and include them in /assets/css/main.scss

@import
  "jupyter-light",
  "jupyter-dark"
;

. Now jupyter notebooks have correct color and style rednering even when the site changes from light theme to dark theme! 👍🏻

(Optional) We can further move the universal <head> section in the beginning of all jupyter notebook to post-jupyter.html and only embed content between <body> tags in the markdown file to solve local and global <head> conflicts.

The following is the example of jupyter notebook embedding.