How I link code in blog posts
Here is a summary of how to link code in jekyll websites.
Markdown Code Snippet
For very fast code blocks that do not need to be synced to an code repo, we can simply wrap code in backticks:
1
Code block!
or with language syntax highlighting:
1
final a = 5
As demonstrated on the chirpy starter blog example.
Github Gists
You can create a github gist which is a single file that is version controlled just like a github repository:
This can be included by copy+pasting the embed script directly into your markdown file:
1
<script src="https://gist.github.com/jakee417/40c236e4ebf6619554276dc9f96408e4.js"></script>
Gist-style code snippets (emgithub)
When you have a code snippet that needs to be synchronized with a code repo, we can use emgithub:
Which was generated by browsing to https://emgithub.com/jakee417/jakee417.github.io/blob/master/_includes/markdown/demo_markdown.md
and copy+pasting the html script that is generated by the website:
1
<script src="https://emgithub.com/embed-v2.js?target=https%3A%2F%2Fgithub.com%2Fjakee417%2Fjakee417.github.io%2Fblob%2Fmaster%2F_includes%2Fmarkdown%2Fdemo_markdown.md&style=color-brewer&type=markdown&showBorder=on&showLineNumbers=on&showFileMeta=on&showFullPath=on&showCopy=on"></script>
This works for code, markdown, and ipynb files.
emgithub + HTML Templates
If clicking through a website for several links is too inefficient, you can build an html template under _includes
and let jekyll/liquid/js do the work for you:
Code Snippet
Which can be included using jekyll’s include
:
1
{% include embed.html link="https://github.com/jakee417/jakee417.github.io/blob/master/_includes/embed.html" %}
Jupyter notebook (nbconvert
)
When individually linking each code block is impractical, we can embed an entire markdown document:
- Create a Jupyter Notebook which consists of code cells and markdown cells.
- Use
nbconvert
to export the entire notebook to the_includes
directory as a markdown file:1 2
cd path/to/filename jupyter nbconvert filename --to markdown --output ~/path/to/blog.github.io/_includes/markdown/filename.md
- Include the markdown file into your blog with
{% include markdown/filename.md %}
Embedded images/plots (i.e. from matplotlib or seaborn) will be created as static assets that need to be manually copied to the
assets
directory of your blog. Alternatively, you can use a library like plotly to embed html plots directly into your notebook (which require no additional export or copying).
1
2
3
4
5
6
7
8
9
10
11
12
def render_plotly_html(fig: go.Figure) -> None:
fig.show()
display(
Markdown(
fig.to_html(
include_plotlyjs="cdn",
)
)
)
def render_table(df: pd.DataFrame | pd.Series) -> None:
display(Markdown(df.to_markdown()))
Here is an example from my blog where I mix markdown and markdown files seamlessly:
Markdown
Happy blogging!