Fixing failed to extract shortcode Errors in hugo server

failed to extract shortcode

* This page contains promotional content

The situation

At the moment I manage the Markdown for this blog on Gitllab and write the posts on a local machine with Git.

The flow is: clone from Gitlab to a local Mac or Linux box with Git, write a post, and push after compiling.

Hugo has a server mode, and if you start it with hugo server -w you can check a preview of the post you wrote at localhost:1313.

The symptom

However, when running hugo server -w, the following error sometimes appears.

(The Hugo theme I currently use is Beautifulhugo)

Error: Error building site: “/tmp/test/content/post/mermaid-sample.md:18:1”: failed to extract shortcode: template for shortcode “mermaid” not found

The error above is about mermaid, but it can just as well be gallery. In short, it seems to be an error saying “you wrote a shortcode, but no such shortcode exists!”

The cause

When the theme inside Hugo is set up using the Git submodule mechanism, the cause is that the submodule is not fetched when you git clone.

In other words, the Hugo layout looks like the following, but if you simply git clone it, the submodule theme inside themes is empty.

The shortcode written in the post goes looking for a template file inside themes/, so it errors out

├── archetypes
├── content
├── layouts
├── resources
├── static
└── themes

The fix

It is solved by fetching the theme inside themes at git clone time as well.

If you are not managing it as a submodule, a normal git clone is fine

$ git clone https://gitlab.com/user/test.git

When you have a submodule setup like this one, all you need is to fetch the submodules as well when you git clone, as below

$ git clone --recurse-submodules --depth 1 https://gitlab.com/user/test.git

Doing it this way makes the submodule inside themes get fetched too.

The fix, part 2

I keep forgetting recurse-submodules, doing a plain git clone and running into this error, but in fact you can fetch the repository managed as a submodule after the git clone too.

How to update the submodule after git clone

$ git submodule update --init --recursive

With this Hugo setup where the Beautifulhugo theme is a submodule, it looks like this

$ git submodule status
-1ff3894b84b1802433b58e22dd22f4eb46a49fa9 themes/beautifulhugo

$ git submodule update --init --recursive
Submodule 'themes/beautifulhugo' (https://github.com/halogenica/beautifulhugo.git) registered for path 'themes/beautifulhugo'
Cloning into '/private/tmp/test/themes/beautifulhugo'...
Submodule path 'themes/beautifulhugo': checked out '1ff3894b84b1802433b58e22dd22f4eb46a49fa9'

I keep running into this symptom, so I left this here as a note to myself