HUGO

How to Open Link in New Tab with Hugo's new Goldmark Markdown Renderer in v0.62.0

In v0.62.0, Hugo has switched to the new Goldmark Markdown Renderer by default, instead of the Blackfriday renderer used previously. Goldmark also introduces a new way to add Markdown Render Hooks to control custom behaviour, e.g. image processing or opening links in new tabs by adding target="_blank" attribute to the links.

I’ve written an article detailing the Goldmark changes as well as how to configure Markdown Render Hooks here: https://agrimprasad.com/post/hugo-goldmark-markdown/

TLDR of the article is that if you just want to be able to open links in new tab for your Hugo site, create a file at layouts/_default/_markup/render-link.html with the following content:

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

Thanks, it was helpful. However, using it in my blog, I have found out it could be improved even more:

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

{{ .Text | safeUrl }} handles a corner case where you render link which is marked as code, e.g. [`hrefTargetBlank`](http://example.com/hugo-docs) doesn't work. Without | safeHTML the link text it is rendered verbatim as <code>hrefTargetBlank</code> instead of being styled as code.

See the related merged PR to the Hugo documentation.

1 Like