Correctly render links with fragments on docs pages

Our previous render hook to create links would drop the fragment when
linking to headings within the current page or within other markdown
pages on the site.

This change parses the URL and formats the link correctly if it includes
a fragment. If the link is a header on the current page, it is rendered
as `http://<current-url>/#header`. If the link is a header on a
different page (e.g. page.md#header), it is rendered as
`http://<page-url>/#header`.

This change is taken from the following Hugo community support post:
https://discourse.gohugo.io/t/markdown-render-hooks-github-and-hugo-compatible-links/22543/14

Signed-off-by: Bridget McErlean <bmcerlean@vmware.com>
pull/3567/head
Bridget McErlean 2021-03-11 19:01:51 -05:00
parent 2cddda84c5
commit 43f52f1aea
1 changed files with 6 additions and 1 deletions

View File

@ -1,5 +1,10 @@
{{ $link := .Destination }}
{{ if not (strings.HasPrefix $link "http") }}
{{ $link = (.Page.GetPage .Destination).RelPermalink }}
{{ $url := urls.Parse .Destination }}
{{- if $url.Path -}}
{{ $fragment := "" }}
{{- with $url.Fragment }}{{ $fragment = printf "#%s" . }}{{ end -}}
{{- with .Page.GetPage $url.Path }}{{ $link = printf "%s%s" .RelPermalink $fragment }}{{ end }}
{{ end }}
{{ end }}
<a href="{{ $link | safeURL }}">{{ .Text | safeHTML }}</a>