How to open links from Hugo posts in the new tab
In a Hugo-powered website, it is possible to open all absolute links in a new tab. To achieve this, you have to use the Goldmark renderer, which is luckily the default library used for Markdown in Hugo from version 0.60 onwards.
Hugo provides a feature called Render Hooks, which allows you to override the default Markdown rendering functionality with your own custom templates. By creating templates with base names of render-{kind}
in the layouts/_default/_markup
directory, you can override certain parts of the default Markdown rendering to HTML.
To open links in a new tab, you can create a file named render-link.html
in the layouts/_default/_markup directory
, with the following code:
<a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}{{ if strings.HasPrefix .Destination "http" }} target="_blank" rel="noopener noreferrer nofollow"{{ end }}>{{ .Text }}</a>
This code checks if the link destination starts with “http”, and if it does, it adds the target="_blank" rel="noopener noreferrer nofollow"
attributes to the link tag. This will cause the link to open in a new tab. If the link does not start with “http”, it will open in the same tab.