Link with anchor has leading slash

[linktext](#id)

renders to

<a id="/#id">linktext</a> (with leading slash)

instead of

<a id="#id">linktext</a> (without leading slash)

My layouts/_default/_markup/render-link.html looks like this

<a href="{{ .Destination | safeURL }}">{{ .Text | safeHTML }}</a>

What did I wrong?

(In the table of contents generated by Hugo there are no leading slashes in the href attributes. So this works fine.)

After some testing I found out that the leading slash comes from the safeURL function.

So here is a quick and dirty solution for my problem:

<a href="{{ if eq (substr .Destination 0 1) "#"}}{{ .Destination }}{{ else }}{{ .Destination | safeURL }}{{ end }}">{{ .Text | safeHTML }}</a>

If the .Destination begins with an # the safeURL function won’t be applied.

Anyway, why does the safeURL function put a slash in there? :unamused:

It’s not 100% true that this is the solution. The slash comes from the template you used before. It depends on how you evaluate the URL. If your baseURL parameter is maybe set to a slash this might be added.

You show only how render-link is handling the links, but not what exactly is handed over to that specific link that is doing that hash thing. Nor do we know where exactly this link happens. I think it might be good to experiment around with RelURL and it’s friends:

1 Like

The [linktext](#id) is from an content article. The baseURL has no slash at the end.

I don’t understand how the relURL function would help in my case.

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