Having trouble tracing how Hugo works in order to change an implementation…
I use a custom parameter on article pages canonical to override the canonical URL of the current page (I syndicate content across two sites but tell indexers which one is correct). For content pages in the site, I create links using the ref shortcode:
{{< ref "internal-page-link" >}} or {{< ref "/blog/internal-page-link" >}}
What I’d like to do is change how this link is rendered to use a conditional instead of using the target page’s Permalink, to use a conditional (if canonical is set, use that, otherwise use Permalink).
I thought i could do this within the render_link.html hook, but seems the link I get in the Destination property is a URL, not a Hugo page (the Page passed in is the source page, not the target).
Any suggestions how I can do this? My goal is for all internal links to point to the intended canonical URL of the page, not the internal one.
The ref and relref shortcodes are, for the most part, not terribly useful when compared to link render hooks. In my view they are legacy features.
You should use a link render hook, starting with the embedded link render hook as a model:
Then make these changes:
diff --git a/layouts/_default/_markup/render-link.html b/layouts/_default/_markup/render-link.html
index 30e4d2660..1210dd1f5 100644
--- a/layouts/_default/_markup/render-link.html
+++ b/layouts/_default/_markup/render-link.html
@@ -15,6 +15,13 @@
{{- with $u.Fragment -}}
{{- $href = printf "%s#%s" $href . -}}
{{- end -}}
+
+ {{- if eq .ResourceType "page" }}
+ {{- with .Params.canonical }}
+ {{- $href = . }}
+ {{- end }}
+ {{- end }}
+
{{- end -}}
{{- end -}}
{{- $attributes := dict "href" $href "title" (.Title | transform.HTMLEscape) -}}
Example:
git clone --single-branch -b hugo-forum-topic-49859 https://github.com/jmooring/hugo-testing hugo-forum-topic-49859
cd hugo-forum-topic-49859
hugo server
Interesting… one thing I’ve liked about the ref/refrel shortcodes is they validate the link on builds.
That little snippet you used in the render hook is what I was missing… I hadn’t considered the ResourceType check… thanks! So Hugo determines on the fly if it’s just a regular external link, but if there’s no protocol, it maps it to a Hugo resource (page/section/resource) which is reflected by this property?
I’m already using the render hook to add some URL parameters under certain circumstances. I’d much prefer to add this to the render hook.