Opening external links in a new tab using the embedded link hook

I am trying to adapt the embedded link render hook to open external links (links that point to outside the current website) in a new tab. Here is what I got,

<!-- https://github.com/gohugoio/hugo/blob/master/tpl/tplimpl/embedded/templates/_markup/render-link.html -->
{{- $u := urls.Parse .Destination -}}
{{- $href := $u.String -}}
{{- $external := false -}}
{{- if strings.HasPrefix $u.String "#" -}}
  {{- $href = printf "%s#%s" .PageInner.RelPermalink $u.Fragment -}}
{{- else if strings.HasPrefix $u.String "http" -}}
  {{- $external = true -}}
{{- else if and $href (not $u.IsAbs) -}}
  {{- $path := strings.TrimPrefix "./" $u.Path -}}
  {{- with or
  ($.PageInner.GetPage $path)
  ($.PageInner.Resources.Get $path)
  (resources.Get $path)
  -}}
    {{- $href = .RelPermalink -}}
    {{- with $u.RawQuery -}}
      {{- $href = printf "%s?%s" $href . -}}
    {{- end -}}
    {{- with $u.Fragment -}}
      {{- $href = printf "%s#%s" $href . -}}
    {{- end -}}
  {{- end -}}
{{- end -}}
<a
  href="{{ $href }}"
  {{- with .Title }}
    title="{{ . }}"
  {{- end }}
  {{- with $external }}
    target="_blank"
    rel="noopener noreferrer"
  {{- end }}
>
  {{ .Text }}
</a>
{{- /**/ -}}

Does this look okay? Or–have I missed something important?

not every link starting with http is external

  • http/my-doc-about-http/
  • http://current-site/

and in development:

  • http:/localhost

Sure, there are false positives, but I think I can live with them. Unless of course there is a better way?

if you can. false positives tend to pop up some time later.

just note down never use absolute urls to your own site in sources … :wink:

I added PDF detection as well: New window fix | Hugo Codex

You can improve it by checking if the baseURL is in the href. In that case it is not an external link.

Just because you can doesn’t mean you should.

https://www.digital.ink/blog/website-links-new-tab/

1 Like

I think I like the idea of adding a visual cue that the link will open in a new tab.