Hugo - Open External Links in a New Tab

Posted on Jan 11, 2021

It is a best practice to have links internal to your site open in the same tab, but links to other sites open in a new tab. This is not, however, the default behavior in Hugo. By default Hugo opens all links in the same tab.

History - Blackfriday Implementation

Previously Hugo used Blackfriday as the markdown processor, but updated to using Goldmark . In Blackfriday it was possible to update a setting in the Hugo config file in order to open external links in a new tab.

# config.toml
[blackfriday]
hrefTargetBlank = true

This will still work, but it will update your Hugo site to use Blackfriday instead of Goldmark to parse your markdown. Hugo moved to Goldmark from Blackfriday because it is faster and CommonMark compliant . This may not be a problem for you, but since it is possible to implement this behavior in Goldmark, we may as well stick to the choices Hugo made.

Goldmark Implementation

The implementation in Goldmark is a bit more complicated than in Blackfriday, but it is also more customizable. You can customize how Markdown is rendered in Hugo using Goldmark by creating specific files .

Implementation

In our case we want to create the file, layouts/_default/_markup/render-link.html, and add the following:

<!--layouts/_default/_markup/render-link.html-->

<a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}{{ if strings.HasPrefix .Destination "http" }} target="_blank"{{ end }}>{{ .Text | safeHTML }}</a>

How it Works

What this does is adds target="_blank" to the link HTML if the link has “http” in it.

target="_blank" is the HTML to open a link in a new tab.

In Hugo internal links can be referenced with relative URLs, for example, [check out this post](/post/hugo.md]. External links, on the other hand have to have the complete URL in order to go to the correct domain, for example [external link](https://www.gohugo.io).

This is useful to know because once you have added this you could have an internal link open in a new tab, if you wanted, by putting in the full link with the http. This can also work against you. If you have a post that has “http” anywhere in the path, like [what is https](/post/what-is-https), it will get opened in a new tab, even though it is an internal link.

Customization

It is possible to also add other tags to external links. For example, if you do not want the sites you are linking to to know the traffic came from your site you could add rel="noreferrer noopener":

<!--layouts/_default?_markup/render-link.html-->

<a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}{{ if strings.HasPrefix .Destination "http" }} target="_blank" rel="noreferrer noopener"{{ end }}>{{ .Text | safeHTML }}</a>

With this file you can go much further than just adding tags to external links and customize it in whatever way you want, but external links is a good place to start and maybe end.