Super Simple Code Highlighting for Ghost

Ghost has a neat feature called Code Injection that allows you to add any code you want to your blog's header and footer without messing around in theme files.

You can use Code Injection to add code highlighting to your blog's code blocks really quickly...

First, open your admin area and visit the Code Injection screen - you'll see two code editors, one for the blog's header and one for the footer.

The header code is injected right before the closing </head> tag so it's perfect for adding additional styles to your blog. Go ahead and pull in the prism.js stylesheet:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.16.0/themes/prism.min.css">
<style>
    pre[class*=language-] {
        margin: 1.75em 0;
    }
</style>
Note: I've added an additional style for pre[class*=language-] here, this is needed to match the padding around code blocks to the default Casper styles

Next up the footer is the best place to add the prism.js JavsScript so that it doesn't block your page from rendering:

<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.16.0/prism.min.js"></script>

Hit save on the Code Injection screen and... that's it!

Well, almost, there's one slight change you need to make when writing your fenced code blocks. Prism.js doesn't auto-detect the language being used so you need to provide a hint like so:

```javascript
console.log('Hello, World!');
```

Extras

It's worth exploring the Prism.js website and checking out what's available on the cdnjs prism repository. There are some neat plugins and additional syntax themes available.

One final note - because MarkDown doesn't let you add classes to fenced code blocks directly, you sometimes need to massage the HTML with JS a little before initialising prism.js. For example, here's how I implemented the line-numbers plugin:

Header:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.16.0/themes/prism.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.16.0/plugins/line-numbers/prism-line-numbers.min.css">

<style>
    pre[class*=language-] {
        margin: 1.75em 0;
    }
</style>

Footer:

<script>
    window.addEventListener('DOMContentLoaded', (event) => {
        document.querySelectorAll('pre[class*=language-]').forEach(function(node) {
            node.classList.add('line-numbers');
        });
        Prism.highlightAll();
    });
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.16.0/prism.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.16.0/plugins/line-numbers/prism-line-numbers.min.js"></script>
Mastodon