Syntax highlighting in Hugo with Highlight.js

I wanted syntax highlighting in Hugo for code snippets, and I wanted it fast.

I didn’t want anything complicated on the server like Pygments. Among the solutions suggested in the Hugo documentation is Highlight.js.

Briefly, Highlight.js uses Javascript to render things between <pre><code> and </code><pre> with the kind of syntax highlighting you expect in your favorite code editor.

Here’s how I made it happen.

In the /layouts directory in your Hugo installation, create a directory called /partials, and in that directory create a file called header.includes.html that contains the following code from the Hugo documentation site:

<link rel=“stylesheet” href=“//”>
<script src=“//”></script>

Once you have this set up, put code snippets in your post between <pre><code> and </code><pre> tags, and they will have syntax highlighting (rendered client-side) in your live posts.

I haven’t even begun to explore the many styles that can be applied to your highlight.js-ified code snippets, but you can see an interactive demo on the project’s home page and a more detailed one here.

To change the look, you call different CSS. Easy as pie.

Update I’m not sure if any of these solutions handles HTML/XML markup all that well. To make it work, you have to escape the < and > with &lt; and &gt; respectively. Not the worst scenario, but certainly a pain in the ass. This might be enough to get me looking at other solutions.

Update: After looking at 140+ Hugo themes, I am currently using the now-newest Hugo theme, Minos, which has highlight.js syntax highlighting baked in.