How can I open links in a separate tab using render hooks and the rel attribute?

Hello,
I would like to open external links, those with https in the URL, in a new tab. I recently switched from using Org mode syntax to Markdown for content and I noticed that Markdown supports render hooks. According to the documentation, the following code adds a rel attribute to external links:

{{- $u := urls.Parse .Destination -}}
<a href="{{ .Destination | safeURL }}"
  {{- with .Title }} title="{{ . }}"{{ end -}}
  {{- if $u.IsAbs }} rel="external"{{ end -}}
>
  {{- with .Text }}{{ . }}{{ end -}}
</a>
{{- /* chomp trailing newline */ -}}

However, from what I’ve noticed, browsers don’t seem to recognize the rel attribute on its own or take any action based on it. I think I should use JavaScript in this case. Right? Or would it be better just to add target="_blank"? Personally, I try to avoid using JavaScript unless absolutely necessary, as some users may have it disabled.

Do you think something like this is allowed in a render hook, or does my modification not conform to the intended use?

{{- $u := urls.Parse .Destination -}}
<a href="{{ .Destination | safeURL }}"
  {{- with .Title }} title="{{ . }}"{{ end -}}
  {{- if $u.IsAbs }} rel="external" target="_blank"{{ end -}}
>

I would be grateful for any suggestions.

Use the target attribute: <a>: The Anchor element - HTML: HyperText Markup Language | MDN

No need for JavaScript.

1 Like

Why would the render hook care if you open a link in a new tab? Your users might not like it, but the render hook has no idea what attributes you put in the a element. Or if you even use an a element. All it does is execute the code you tell it to execute.

Goodness, no. Use target or better still search the net whether opening a link in a new window/tab is a good idea. And check the documentation on MDN – rel=external has no functionality, it’s just a marker for CSS.

1 Like

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