How to add syntax highlighting to Posthaven
I recently gave Posthaven a shot for hosting my blog. While ultimately I decided to go with Ghost instead due to the lack of a few features (syntax highlighting, custom URLs, image headers, markdown support), I tried to dirty my hands and hack together a solution that would allow me to enable syntax highlighting on their platform, and I was able to get it working (using highlight.js). So just in case this helps someone else, I'll leave my solution here.
When writing a new post on Posthaven, you are able to enter some rudimentary custom HTML to the post (no classes, limited elements, but it works™️).
So first things first, when writing your post, you can go into the custom HTML tab, and enter your code inside a <code>
element, like so:
<pre><code>
console.log("Hello World!"); // hello!
</pre></code
Anything inside the <pre><code></code></pre>
blocks will get syntax highlighted, and the language will be detected automatically.
Here's how to get syntax highlighting working:
- Select your site name in the dashboard, go to Settings, Theme, and under Your Themes, hit Manage.
-
Under the Manage Your Themes section, you will see a New Theme button. Click that button, and clone from any of the existing themes that you like best.
-
Go back to the Manage Your Themes section, and under the theme you just created, you will see a Edit button. Click that.
- You will see an option to pick the file you want to edit. We will edit the layouts/theme.liquid file.
Inside the <head>
section, add this code:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/styles/solarized-dark.min.css" />
And just before the closing body tag </body>
, add this code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/highlight.min.js" type="text/javascript"></script>
<script>hljs.initHighlightingOnLoad();</script>
After this, set your newly created theme as the active theme on your Posthaven blog, and you will be able to see your code syntax highlighted when you open a post.