Open external links in new tab/window

Hi there.
I used this code snippet here to change the rendering of all links starting with http

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

I put it on multiple lines here in the forum. You want to place it on one line ideally.

Basically what it does ist, that it looks at the link and adds the _blank and noopener and noreferrer to it when the link starts with http. This works for http and https of course.

Place this snippet in a file called render-link.html and put this file into the directory <hugo_root>/themes/<your_theme>/layouts/_default/_markup/

Works for me like a charm.

2 Likes

If you don’t need it to be statically compiled, and you’re looking at only opening external domain links to a new tab, you could also run an onload JavaScript script to do this on the fly.

I run a script similar to this on all my sites which is super light weight and it’s never failed: Open External Links In New Window | CSS-Tricks

This also let’s you later add things like an interstitial, or a dialog/confirmation for external links. You just need to ensure you add the appropriate checks for mailto, tel, and modal links if any.

Solved my problem before I even knew I had one. Thanks for sharing!

1 Like

Some people might want to open PDF’s in a new window. I use this code for that:

1 Like