Auto-linking URLs with Hugo

In May, I decided that I would start to publish more content types on my site, such as short notes (similar to tweets) as well as bookmarks and replies.

This was fairly straightforward, but one issue I had with this was that my content was purely plaintext, which meant that if I were to include a URL in a post's body, it would not be converted to a clickable HTML link.

This was fine for a little bit, as I've been not doing too much with it, but over the last month or so I've been starting to publish a lot more on my site using my Micropub server.

To make it possible to convert these to links for better user experience, both for automated parsing of the posts and humans viewing the posts, I needed to delve into some dark magic and use a regular expression (slight sarcasm!).

I managed to adapt a JavaScript version of the regex to work with Hugo's Regular Expressions functionality, which led me to the following:

{{ replaceRE "(https?://[a-zA-Z0-9\\-._~:/?#\\[\\]@!\\$&'()*\\+,;%=]+)" "<a href=\"$1\">$1</a>" .Content | safeHTML }}

Notice that we need to make sure that Hugo allows the HTML we've just injected, so add on a pipe to [safeHTML], otherwise it'll render the tags as text not HTML.

And that's it, you now have auto-linking URLs! You can see it in action in my message to Aaron Parecki.

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#hugo #www.jvt.me #blogumentation.

This post was filed under articles.

Has this content helped you? Please consider supporting me so I can continue to create content like this!

Related Posts

Other posts you may be interested in:

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.