Adding Audio to Hugo
By John
The website you are reading was generated using Hugo. I recently upgraded the version of Hugo up quite a few releases.
Overall everything went smooth, but something I didn’t catch till the next day was all my audio embeds stopped working. The embedded html5 audio tag in the post or page was being ommited. It was getting rendered as an html comment, “raw HTML omitted.”
<!-- raw HTML omitted -->
Considering I was upgrading from v 0.40 to v 0.80 I think I got off pretty easy. Note to self, don’t wait two years to upgrade next time. That’s the beauty of Hugo though, since it’s a static site renderer you don’t have to worry about those security patches the same way you would if you were running WordPress, Drupal or Ghost. Waiting two years to upgrade WordPress means you probably got hacked.
The problem arose out of a later version of hugo turning off embeded html by default. I think that’s a great decision, but it did break my html5 audio. If something like this happened to you, you can re-enable embedded html by adding this to your config.toml.
[markup.goldmark.renderer]
unsafe= true
Ultimately I didn’t like that solution so I opted for the better solution which is to create a shortcode to handle your audio embeds. This also makes global audio player changes considerably easier.
Embedding audio with Hugo shortcodes
Creating shortcodes in Hugo is very simple. All you need to do is add an html file in the shortcodes folder with the html you want to render. The templates are typical go templates that leverage the html/template and text/template core libraries. Even if you are not a Go dev, you will probably find them straightforward to edit.
I started out with trying an example from the zen theme.
To make a custom audio shortcode create an html file in the following location.
layouts/shortcodes/audio.html
Add this to the file.
<figure {{ with .Get "class" }}class="{{ . }}"{{ end }}>
<audio controls preload="{{ .Get "preload" | default "metadata" }}">
{{ with .Get "src" }}<source src="{{ . | relURL }}" type="audio/mpeg">{{ end }}
</audio>
{{ with .Get "caption" }}<figcaption>{{ . }}</figcaption>{{ end }}
</figure>
In your page or post all you need to do is add the audio shortcode and it will populate an embeded html5 audio player in your content. For example…
{{<audio src="/media/audio/your-audio-file.mp3" caption="your caption" >}}
To learn more about custom shortcodes, check out the hugo docs at https://gohugo.io/templates/shortcode-templates/.
For more on general template details visit https://gohugo.io/templates/introduction/.
Docker Hugo
BTW If you need a simple Hugo Docker image, try this one. I use it on my laptop when writing new posts. Hugo Docker image
docker pull arroyolabs/go-dev:hugo
The official Hugo image is 3 years out of date, ouch! This one is better than that.