Anchor point in html

Publish date: Sep 13, 2021
Tags: Programming

Whom’s this for?

For Hugo users who want to make a table of contents for each post. And the website will navigate to corresponding section when clicking on the heading.

Where is the file?

The file is usually named “toc.html”(table of contents) in the layout/partials folder.

My “toc.html” looks like the following.

{{ $headings := findRE "<h2.*?>(.|\n])+?</h2>" .Content }}
{{ if ge (len $headings) 2 }}
<div class="child-borders">
  <div class="toc border" aria-labelledby="toc-heading">
    <h2 id="toc-heading">Table of contents</h2>
    <ol>
      {{ range $headings }}
        <li>
          {{ $id := findRE "id=\".*\"" . }}
          {{ $id = index $id 0 }}
          {{ $id = strings.TrimPrefix "id=\"" $id }}
          {{ $id = strings.TrimSuffix "\"" $id }}
          <a href="#{{ $id }}">
            {{ . | htmlUnescape | plainify }}
          </a>
        </li>
      {{ end }}
    </ol>
  </div>
</div>
{{ end }}

What is happening there?

Then from the elements of website I found the anchor points in my posts are like id="load-the-data" from the heading tag, or variable {{.}}, <h2>Load the data</h2>.

Noticing that the language in {{}} is golang, I modified the regular expression and processing pipelines as below.

{{ $id := findRE ">.*<" . }}
{{ $id = index $id 0 }}
{{ $id = strings.TrimPrefix ">" $id }}
{{ $id = strings.TrimSuffix "<" $id }}
{{ $id = strings.Replace $id " " "-" }}
{{ $id = strings.ToLower $id}}

Now the table of contents works as expected :)