Adding Syntax Highlighting to Ghost using Prettify

If you are using the Ghost blogging platform for Node.js, you will probably have noticed that code snippets are not automatically styled. That's because Ghost doesn't have a syntax highlighting feature, yet. Hopefully, that's going to be a Ghost plug-in one day, but for now you'll have to rely on third-party libraries.

There are several syntax highlighting JavaScript libraries out there. I personally prefer Google's Prettify, and in this tutorial I'll show you how to use it with Ghost.

Linking to CDN

The easiest method to enable Prettify is to include, in the header section of your theme's default.hbs, the script tag below:

<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>

Once your page has finished loading, Prettify will look for <pre>, <code>, or <xmp> tags with the prettyprint class, and colorize the contents. Since Ghost blog posts are written in Markdown, and all HTML is valid Markdown, you can insert your code snippets in <pre> blocks directly in the Ghost post editor, like shown below:

<pre class="prettyprint">class Voila {  
public:  
// Voila
static const string VOILA = "Voila";

// will not interfere with embedded <a href="#voila2">tags</a>.
}</pre>

If you want to enable line numbers, just add the class linenums. There are also several ready-made themes to choose from, which you can select using the skin parameter.

Something else worth noting is that all HTML code inside <pre> or <code> blocks will be rendered by the browser as HTML. So, if you just want to display HTML code with syntax highlighting, make sure to replace the special characters < and >, with &lt; and &gt; respectively.

Hosting on your server

If you don't want to link to the CDN, you can alternatively host Prettify on your server. Download the script and default style, and load them in the header section of your theme's default.hbs:

<link href="prettify.css" type="text/css" rel="stylesheet" />  
<script src="prettify.js"></script>

Then, once your page has finished loading, run the prettyPrint function:

window.addEventListener('load', function() {  
  if (prettyPrint) {
    prettyPrint();
  }
});

You can find out more information about Prettify in the official code repository hosted on GitHub.