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.
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>
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.
Thanks @briggySmalls. In fact there is a difference even in comparison to my linked PR :).
However, as it is a text context and can contain different elements it would be even better to use safeHTML instead of safeURL. Unfortunately, I’m no longer able to edit that post. Therefore, the updated line here, again:
<a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}{{ if strings.HasPrefix .Destination "http" }} target="_blank"{{ end }}>{{ .Text | safeHTML }}</a>
Just what I was looking for. Thanks. I tried a few things but could not figure out how to also make this work with mailto links. I duplicated the line and changed http to mailto and that made duplicate links.
I tried a new render-mailto.html file which did nothing. I guess some type of if statement in the render-link.html so it picks up either http or mailto … I know that this is a minor edge case using gmail but inquiring minds and all.
<a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}{{ if strings.HasPrefix .Destination "http" }} target="_blank"{{ end }}>{{ .Text }}</a>
Can it be adapted that it opens .pdf documents from my site also in a new tab?
I’m not familiar with the functions, but it seems if strings.HasPrefix .Destination “http” seems to verify that the destination starts with http. Unfortunately I haven’t found a HasPostfix function. So I don’t have any idea how to achieve this.