Embedding audio with Hugo shortcodes
An audio player only needs a few lines of HTML, but repeating those lines in Markdown gets tedious. A Hugo shortcode keeps the markup in one place and gives each post a much cleaner way to embed an MP3.
Create layouts/shortcodes/audio.html:
<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>
Then use it in a content file:
{ { < audio src="/audio/file.mp3" caption="Caption" > } }
The shortcode accepts a source URL, an optional caption, and an optional CSS class. It also defaults preload to metadata, so the browser can read details such as the audio duration without downloading the whole file immediately.
If you need several audio formats, extend the shortcode with more <source> elements. For a site that only publishes MP3 files, I would keep it this small.
Enjoyed reading this?
If you found this article helpful, consider supporting my writing. Every little bit helps keep this blog going.
Related articles
- Customizing Hugo’s RSS Feed
Adjust Hugo RSS titles, descriptions, content, and section filtering while keeping the generated feed valid and easy to discover.
- Organizing Hugo Content With Tags and Categories
Organize Hugo content with a small, deliberate set of tags, categories, or custom taxonomies that lead to useful archive pages.
- A More Useful 404 Page in Hugo
Turn Hugo's 404 page into a useful route back to the homepage, search, or content visitors may have wanted.