Fail build if cross reference (URL) doesn't exist

In the docs there is a part about cross references. If the referenced document doesn’t exist, the build fails.

What about links like [My link](/myurl)? I want that the build fails if \myurl (which I defined in front matter with the url parameter) doesn’t exist.

Is this possible in Hugo?

Yes. Use the ref or relref function within a render hook.

I tried

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

and

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

but both didn’t work.

Please post an example of your frontmatter.

content/topic1/subtopic1/_index.md

---
url: "myurl"
---

and I want to link to this page from content/topic33/subtopic23/subsubtopic2/_index.md (just to illustrate the complex tree).

If you want to link to content/topic1/subtopic1/_index.md using [Subtopic 1](/myurl), there is no way that I know of to perform error checking on the URL.

If you want to link to content/topic1/subtopic1/_index.md using [Subtopic 1](topic1/subtopic1), you can perform error checking in a render hook using ref or relref:

{{- $url := urls.Parse .Destination -}}
{{- $remoteSchemes := slice "http" "https" "mailto" -}}
{{- $isRemote := in $remoteSchemes $url.Scheme -}}
{{- if $isRemote -}}
  <a href="{{ .Destination }}" target="_blank" rel="noopener">{{ .Text | safeHTML }}</a>
{{- else -}}
  <a href="{{ ref .Page .Destination }}">{{ .Text | safeHTML }}</a>
{{- end -}}
1 Like

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