Render-link hook behaves unexpected for different shortcode call syntax

I am not sure if this is a bug or just my lack of understanding, but

[posts]({{% ref "posts/" %}}) with `%`

behaves differently to

[posts]({{< ref "posts/" >}}) with `<`

I have a render-link hook that parses the URL and adds a target=_blank if the URL is an external URL identified by a http:// prefix.

{{- $page := .Page }}
{{- $content := .Text }}
{{- $url := .Destination }}
{{- $title := .Title | default "" }}
{{- $title = trim $title " " }}
{{- $target := "" }}
{{- if or (strings.HasPrefix $url "http://") (strings.HasPrefix $url "https://") }}
  {{- $target = "_blank" }}
{{- end -}}
<a href="{{ $url | safeURL }}"{{ if $title }} title="{{ $title }}"{{ end }}{{ if gt (len $target) 0 }} target="{{ $target }}"{{ end }}>{{ $content | safeHTML }}</a>

This test fails for the second shortcode call syntax and I currently have no clue why that is.

Minimal working example

hugo v0.119.0-b84644c008e0dc2c4b67bd69cccf87a41a03937e windows/amd64 BuildDate=2023-09-24T15:20:17Z VendorInfo=gohugoio

Without answering your question, are you sure you really want to do that? I think many find it to be an annoying practice, and there are several good reasons not to do it:

https://www.digital.ink/blog/website-links-new-tab/

1 Like

I know about that and “in real life” it is configurable.

Put this at the top of your render hook:

{{ warnf .Destination }}

And see this:

https://discourse.gohugo.io/t/destination-from-rel-or-relref-does-has-unexpect-prefix/42848/2?u=jmooring

Okay, technically I understand now.

Does this mean that calling ref / relref in pages with render-image hooks that may parse the destination is only allowed to be called with %?

From a user standpoint this seems to be pretty impossible as they are now in the need of knowing implementation details of the used theme.

Yes

True, but the ref and relref shortcodes aren’t terribly useful with a render hook that resolves links via the GetPage method on a Page object. This article might be helpful.

I hesitate to call them obsolete, but I think they are.

3 Likes

Thanks, Joe!

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