Adding syntax highlighting to Ghost's default theme
[This approach as subsequently started to fail for me, so I have switched to the technique outlined for using Prism; it's a bit manual to have to list every language you want highlighted, but it works with the Casper 2.2.1 theme]
When moving this blog from Silvrback to Ghost(Pro) the one thing I had to figure out was how to get syntax highlighting for source code. Silvrback supported the GitHub-style code block markup, e.g.:
```python
def foo(): pass
```
Ghost's default Casper theme, though, has no included syntax highlighting (I assume so every blog doesn't have to pay the overhead cost). That meant I had to find a solution to this problem, else I would not be switching to Ghost.
In the end I found highlight.js. It's hosted on Cloudflare so I was able to use Ghost's Code Injection feature to add the appropriate tags in the header (and specify a non-default theme to get richer Python highlighting):
<!-- Agate theme -->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/styles/agate.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/highlight.min.js"></script>
The only real hitch is that the on-load registration that highlight.js uses doesn't seem to mesh with Ghost and/or the Casper theme. In the end I just followed the docs for highlight.js to turn on the highlighting in some JavaScript I put in a <script>
tag in the footer (along with tweaking the code to not rely on jQuery):
// https://highlightjs.org/
activateHighlight = function() {
document.querySelectorAll("pre code").forEach(
function(currentValue, currentIndex, listObj) {
hljs.highlightBlock(currentValue);
}
);
}
if (window.attachEvent) {
window.attachEvent('onload', loadHighlight);
} else {
if (window.onload) {
var originalOnload = window.onload;
var newOnload = function(evt) {
originalOnload(evt);
activateHighlight(evt);
};
window.onload = newOnload;
} else {
window.onload = activateHighlight;
}
}
If the above is syntax highlighted then it works. 😊 The last step was to visit highlight.js on libraries.io to register for release notifications. That way I know when I need to update the URLs to newer versions.
Overall not complicated and I'm happy with the final outcome!