Show domain in rendered hyperlinks to guide readers

I’d like to show the domain name in rendered hyperlinks, e.g. [link text](subdomain.domain.com/page) to render as “link text (domain.com)”. This way the readers can see where the link is going (without hovering). I’m quite close but hope somebody can help:

  1. How to get the domain only from the url, without subdomains (e.g. gohugo.io instead of discourse.gohugo.io)? I need to concatenate the last two elements from $splitDomain
  2. How to make this work for internal links when destination is set to a page only. Can I render the full url?

My current render-link.html:

{{ $destination := .Destination | safeURL }} 
{{ $splitDest := split $destination "://" }}
{{ $splitPath := split (index $splitDest 1) "/" }}
{{ $splitDomain := split (index $splitPath 0) "." }}
{{ $domain := (index $splitDomain 0) }}
<a href="{{ .Destination | safeURL }}"{{- with .Title}} title="{{ . }}"{{ end -}}>{{ .PlainText | safeHTML }} ({{ (index $splitPath 0) }})</a>

Hope somebody can give a hint :slight_smile:

See https://gohugo.io/functions/urls/parse/

Specifically, IsAbs and Hostname.

Thanks, this simplifies my snippet, and I found absUrl to normalise my relative & absolute links (this prevents forking the logic when using IsAbs). I now have the following:

{{ $u := urls.Parse (absURL .Destination) }}
{{ $splitDomain := split $u.Hostname "." }}
{{ $domain := (index $splitDomain 0) }}
<a href="{{ .Destination | safeURL }}"{{- with .Title}} title="{{ . }}"{{ end -}}>{{ .PlainText | safeHTML }} ({{ $u.Hostname }})</a>

However, Hostname still includes subdomains, and not only the domain. Any idea how to fix this? How can I take & concatenate the last 2 elements of $domain?

Not absoluetly sure, i find the tocs a little confusing array slice collection but a combination of

  • last 2
  • delimit “.”

Should do the trick

After some more trial and error, I found collections.Last. Combined with @irkode’s suggestion of delimit, I have the following:

{{ $u := urls.Parse (absURL .Destination) }}
{{ $splitHostname := split $u.Hostname "." }}
{{ $domain := delimit (last 2 $splitHostname) "." }}

<a href="{{ .Destination | safeURL }}"{{- with .Title}} title="{{ . }}"{{ end -}}>{{ .PlainText | safeHTML }} ({{ $domain }})</a>

Thanks!

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.