Syntax Highlighting with Hugo (without JS)

If you are into writing code and use Hugo for building a personal or tech blog - then you’ll want syntax highlighting setup for when you show off your code snippets (like we do on this site!) It is also quite simple when you know how.

Some advantages of using this method include not having to download a JS library to do the job (so performance), not having the code flash on load after the JS finishes and not having to manage another library to do a job that’s already included in Hugo.


Step 1) We want to enable the syntax highlighting with pygmentsCodeFences so we add the code below into our config file.

pygmentsCodeFences = true

Step 2) In our example, we’re going to use the classes version with pygmentsUseClasses (so we can change the theme). If this if off then it will still work, but it will use inline style tags and give you less flexibility.

pygmentsUseClasses = true

Step 3) We can turn on line numbers to appear on the left-hand side of the code.

        lineNoStart = 1
        lineNos = true
        tabWidth = 4

Step 4) Choose a theme. Hugo’s syntax highlighting is built on Chroma, which in turn is based on pygments - so if you find pygment themes they should work (and are easier to find).

View Themes on Farbox View Themes on StylishThemes

So there we have it - have any cool themes? Let us know in the comments.

Site illustrations (of Hugo the rabbit) drawn by Carina Roberts.