Creating a clickable link from an anchor generated by hugo

Sometimes you just want a generated anchor link like this:

anchor

Hugo generate by default anchors to headings, but the ‘clickable link’ has to be done manually, or, in my case, I do a post processing in layouts/partials/main.html, my link is inline svg style. The ‘replaceRE’ code is based on another answer that I don’t have the link anymore, but is in the somewhere in discourse hugo. Another detail my site config has uglyurls = true.

{{- block "main" . -}}

    {{- $pageUrl := .Permalink -}}

    {{- $h1Content := .Content | replaceRE "<h1 id=\"([^\"]+)\">([^\"]+)</h1>" (printf "<h1 id=\"$1\">$2<a class=\"anchor\" href=\"%s#$1\"><svg><use xlink:href=\"#icon-link\"></use></svg></a></h1>" $pageUrl) | safeHTML -}}

    {{- $h2Content := $h1Content | replaceRE "<h2 id=\"([^\"]+)\">([^\"]+)</h2>" (printf "<h2 id=\"$1\">$2<a class=\"anchor\" href=\"%s#$1\"><svg><use xlink:href=\"#icon-link\"></use></svg></a></h2>" $pageUrl) | safeHTML -}}

    {{- $h3Content := $h2Content | replaceRE "<h3 id=\"([^\"]+)\">([^\"]+)</h3>" (printf "<h3 id=\"$1\">$2<a class=\"anchor\" href=\"%s#$1\"><svg><use xlink:href=\"#icon-link\"></use></svg></a></h3>" $pageUrl) | safeHTML -}}

    {{- $h4Content := $h3Content | replaceRE "<h4 id=\"([^\"]+)\">([^\"]+)</h4>" (printf "<h4 id=\"$1\">$2<a class=\"anchor\" href=\"%s#$1\"><svg><use xlink:href=\"#icon-link\"></use></svg></a></h4>" $pageUrl) | safeHTML -}}

    {{- $h5Content := $h4Content | replaceRE "<h5 id=\"([^\"]+)\">([^\"]+)</h5>" (printf "<h5 id=\"$1\">$2<a class=\"anchor\" href=\"%s#$1\"><svg><use xlink:href=\"#icon-link\"></use></svg></a></h5>" $pageUrl) | safeHTML -}}

    {{- $h6Content := $h5Content | replaceRE "<h6 id=\"([^\"]+)\">([^\"]+)</h6>" (printf "<h6 id=\"$1\">$2<a class=\"anchor\" href=\"%s#$1\"><svg><use xlink:href=\"#icon-link\"></use></svg></a></h6>" $pageUrl) | safeHTML -}}


    {{- $finalContent := $h6Content -}}
    {{- $finalContent -}}

{{- end -}}

Generated content example in my case:

<h1 id="file-format">
    File Format
    <a class="anchor" href="https://freethebit.gitlab.io/c/introduction.html#file-format">
        <svg><use xlink:href="#icon-link"></use></svg>
    </a>
</h1>

Instead of svg could be anything, icon fonts, whatever you want.

Thanks for this tip @freethebit.

For reference, @kaushalmodi does the same thing, in one line here :slightly_smiling_face:, and I attempt to explain it to myself here.

3 Likes

that’s awesome, thanks. I searched for a long time but those links didn’t come up in search results.

Brilliant explanation, thanks!

1 Like