Add Syntax Highlighting to Your Ghost Blog

Add Syntax Highlighting to Your Ghost Blog

comments

Ghost is a very powerful blogging platform. But by design it doesn't include some of the more feature-rich functionality of other mainstream CMS like syntax highlighting. Don't worry though as it's still quite easy to add this to your site.

There's a few different syntax highlighting libraries available such as highlight.js, Rainbow, and Prism.js. In my opinion Prism.js is the most robust and well documented option available. This is what I use on my site and this is what I'll be using for the purpose of this guide.

Adding Prism.js to your blog

Ideally you'll want to keep the file sizes of prism.js and prism.css as small as possible. There's a handy tool available on the official Prism.js website which allows you to customize Prism.js to your specific requirements.

For my blog I selected the minified version, along with the languages that I'll be using on this site - Apache configuration, Bash, C, C#, C++, CSS, HTML, Java, Javascript, JSON, Markup, Perl, PHP, Python, and SQL.

Once you've generated the prism.js and prism.cs files, you can now transfer them to your server. You'll want to upload them to the following locations:

content/themes/your-theme/assets/js/prism.js
content/thems/your-theme/assets/css/prism.css

Next you'll need to add the link and script tags to your blog. This can be done via editing the default.hbs file.

content/themes/your-theme/default.hbs

Under the {{!-- Styles --}} section you can add the link tag:

{{!-- Styles --}}
<link rel="stylesheet" type="text/css" href="{{asset "css/prism.css"}}" />

And under the {{!-- JavaScript files --}} section you can add the script tag:

{{!-- JavaScript files --}}
<script type="text/javascript" src="{{asset "js/prism.js"}}"></script>  

Marking code to be syntax highlighted

To add some code to your blog post and have it be syntax highlighted, you'll need to add the markdown before and after the code.

Here's an example if you want to display some C language code:

```c
#include 
int main()
{
   printf("Hello, World!");
   return 0;
}
```

Will return:

#include <stdio.h>
int main()
{
   printf("Hello, World!");
   return 0;
}

Example markdown list:

  • ```css
  • ```c
  • ```html
  • ```javascript
  • ```php

The right way & the wrong way

Make sure to put the starting and ending Prism markdown around your code on their own lines. If you put them on the same line as your code, it won't work properly. See example:

markup-proper-syntax

html<b>hello</b>

<b>hello</b>