Hugo xref (Cross Reference) Shortcode

A screenshot of some code

This blog is built with the Hugo static site generator - an awesome way to build a website. While Hugo has some good built in support for cross references I wanted something a little extra - the ability to reference content that doesn’t exist yet. A future cross-reference.

The good news is that, as an engineer, if something isn’t exactly how you want it, you just make it exactly how you want it. - Mark Rober

As I write content, I sometimes have ideas for future posts. When the future me eventually writes those posts, he doesn’t want to have to go back to add references to that content. That’s easy. I could just insert broken cross-references into the current content and they’ll magically start working when the content does exist in the future. But present me is less than thrilled with a bunch of 404’s laying around waiting to happen - some of which may never be resolved if future me is forgets to actually write the content.

The built-in ref and refRel shortcodes will generate links to other content. But they will generate warnings (or errors) if the target content isn’t found.

Enter custom shortcodes - a way to write your own embeddable codes that Hugo will process when compiling the content. I created xref that will emit a <a> tag if the content exists, or just the plain old link text if the content doesn’t exist.

The following code will generate an output where the link that doesn’t exist will just be rendered as text and the link that does exist will be rendered as an actual <a> tag.

{{< xref "does-not-exist.md" >}}This link does not exist, but may in the future{{< /xref >}}
{{< xref "hugo-xref-shortcode.md" >}}This link does actually exist{{< /xref >}}

Alternatively, you can use the normal markdown link syntax if you’re ok with empty href’s being rendered. For example:

[This link does not exist, but may in the future]({{< xref "does-not-exist.md" >}})
[This link does actually exist]({{< xref "hugo-xref-shortcode.md" >}})

It’ll even take into account pages that exist, but are marked as draft - treating drafts as links that shouldn’t exist yet.

Whether or not this is a good idea or not is up for debate. But it serves its purpose for now. It’s very possible that this exists elsewhere, but it was also a learning exercise for me in terms of creating shortcodes - and it served that particular purpose well.

Full code is contained in this gist: