Checking link anchors

Short version: what is the preferred method to create references to anchors on pages and have errors checked at compile time?

Long version:
When I link to another page (using, say, relref), Hugo checks that the page exists (nice! - although, maybe that’s just because I do a .GetPage) so I can avoid errors.

Right now, I build links to anchors by adding “#anchor” to the URL. Is there a way to check that the anchor really is on the page?

Here is what I am using (it works great, but doesn’t do error checking) - you can see where I concatenate the “#” and anchorized string:

{{- /* Mike's first attempt to make a Hugo Template
     * the first param is the page
     * the second param (optional) is the anchor
     */ -}}
{{- $pagename := .Get 0 -}}
{{- $anchorname := .Get 1 -}}
{{- $target := relref . $pagename -}}
[{{- with .Site.GetPage $pagename -}}{{- .Title -}}{{end}}{{- with $anchorname -}}   ({{- $anchorname -}}){{- end -}}]({{ $target }}{{- with $anchorname -}}#{{- anchorize $anchorname -}}{{- end -}})

This is one of those “Hugo is working great, but this could make it even cooler” things.

Thanks!

Not easily. Hugo won’t know what anchors exist on the target page until the target page is fully rendered. I suppose you could .GetPage and then parse the .Content for element IDs and named anchors, but this approach seems fragile and potentially expensive.

1 Like

Makes total sense - the process that fills in those id attributes for the anchors may not be run if the page isn’t processed yet, so this would have to be two pass.

A post-rendering check for anchor links would be great. It should include internal links generated by a render-link.html render hook. As long as there isn’t a built-in option for that, my recommendation is GitHub - wjdp/htmltest: Test generated HTML for problems with the CheckAnchors option enabled.