Monday, January 17, 2022

Source code syntax highlighting on Blogger

Making code look nice on blogger is pretty hard. Most of the time we use a fancy IDE with syntax highlighting to write the code, but once we want to talk about it here on blogger, all we can show is mono-space text... yuck! The best thing I've found so far is to add hightlight.js as part of the theme HTML. Then whenever you add HTML in the form of:
<pre><code>YOUR CODE GOES HERE</code></pre>

it will highlight it. However if you have HTML in the code, you will still need to escape it first using something like https://www.freeformatter.com/html-escape.html. Also highlight.js will try to figure out the language that you're code is in, but if you want to force it, you can by adding a class="language-<ALIAS>" attribute to the <code> element. For instance, to do Typescript:

<pre><code class="language-typescript">class MyClass extends SubClass {
  private field;
  constructor() {}
}</code></pre>
And you'd get something like this:
class MyClass extends SubClass {
  private field;
  constructor() {}
}


Configuration

Blogger doesn't allow <link> elements in the post template so we have to edit the whole theme HTML to add the CSS styles. Goto the dashboard and click on "Theme" then click on the down arrow next to "Customize"


Then click on "Edit HTML"

And paste in the following code somewhere in the <head> section of the HTML
<link href='https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@latest/build/styles/stackoverflow-dark.min.css' rel='stylesheet'/>
<script src='https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@latest/build/highlight.min.js'/>
<script>hljs.highlightAll();</script>
Like this:


You can find other themes on the highlight.js site, but make sure you use the CDN path like I did so you will always get the latest version.

No comments: