How to integrate Prism.js code highlighting with Hugo

Hugo code beautified using Prism.js instead of Chroma

Posted on 31 December 2019

Hugo by default ships with Chroma, however if you wanted to use Prism.js - perhaps due to many plugins, themes and configurable options, this is a very very quick and basic tutorial for beautified code using Prism.js instead of Chroma.

Download Prism JS and Prism CSS

Download Prism.js with any of the configured plugins and theme that you would like to use. Here is one I am using, click the link for my pre-configured options.

https://prismjs.com/download.html#themes=prism-tomorrow&languages=markup+css+clike+javascript+bash+dart+django+docker+git+go+graphql+groovy+http+ini+javadoclike+json+makefile+markup-templating+nginx+php+phpdoc+python+jsx+regex+ruby+sass+scss+sql+toml+twig+yaml&plugins=line-numbers

Copy the downloaded files to Hugo project

Hugo Static Folder

If you want to simply copy the prism.js and prism.css to static folders, Hugo does not process this folder and simply copies the assets to public folder as is. This is the simplest option.

Hugo Assets Folder

If you want to do some clever and funky processing such as minification, concatenation, fingerprinting etc, copy the prism.js and prism.css files to assets folder.

Adding JS and CSS to templates

Edit your head.html or equivalent partial template and include the CSS and JS files.

Hugo Static Folder method

This is the simplest option, if you copied the prism.js and prism.css files to static folder above, edit your template and add:

<script src="/js/prism.js"></script>
<link rel="stylesheet" href="/css/prism.css" />

Hugo Assets Folder method

Using the assets folder and processing the CSS & JS is slightly more advanced. You will need to load the resources, process them and add the link Hugo way. In the example below, we minify the JS and conditionally fingerprint the file if we the site is in production environment.

Processing and adding the prism.js file

{{ $prismjs := resources.Get "js/prism.js" | resources.Minify }}
{{- if (eq (getenv "HUGO_ENV") "production") -}}
  {{ $prismjs = $prismjs | fingerprint "md5" }}
{{ end }}
<script src="{{ $prismjs.RelPermalink }}"></script>

Processing and adding the prism.css file

Almost the same process as above..

{{ $prismcss := resources.Get "css/prism.css" | resources.Minify }}
{{- if (eq (getenv "HUGO_ENV") "production") -}}
  {{ $prismcss = $prismcss | fingerprint "md5" }}
{{ end }}
<link rel="stylesheet" href="{{ $prismcss.RelPermalink }}">