How to add syntax highlighting to ghost posts
Since this blog is made with Ghost it would only make sense to also post about how Ghost works. This does not mean I will post extensive tutorials on how to set it all up, but anytime I encounter a situation where I want to do something with Ghost, but don't know how, I will create a short post with what I learned.
This time I wanted to add a piece of Python code to my blog post and did not know how to ensure you get a nice code block with syntax highlighting.
Thankfully the solution is relatively easy. Ghost already supports the creation of code blocks using three backticks followed by the language, just like markdown. By typing ```python
for example you can initialize a python code block. This does not automatically add syntax highlighting though.
Prism
There are multiple syntax highlighters available, but the one I used was Prism. The way to enable this in Ghost is to make use of the code injection feature. Go to Settings -> Code Injection and add the following to the site header:
<script src="https://cdn.jsdelivr.net/npm/prismjs/prism.min.js" defer></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/plugins/autoloader/prism-autoloader.min.js" defer></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs/themes/prism-tomorrow.min.css">
This uses CDNs to load the javascript dynamically. The theme can be customized on the last line. There are a number of default Prism themes, which can be seen here. Furthermore, a number of additional themes can be found here. The CDN links to the additional themes can be found here.
Custom Themes
In case all those themes are not good enough, it is possible to generate your own custom theme with this theme generator. You can tweak the colors to your liking and simply download the CSS file.
Once you've downloaded the CSS file you need to inject this into the site header as well. The only difference is that this is of course not hosted on any CDN so you need to copy all the CSS code and add it with a style tag as follows:
<script src="https://cdn.jsdelivr.net/npm/prismjs/prism.min.js" defer></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/plugins/autoloader/prism-autoloader.min.js" defer></script>
<style>
/************** INSERT CODE HERE **************/
</style>
And voila, you have code syntax highlighting enabled on your Ghost blog!