I am trying to use table of content for my page. But I need anchor links to lead not to headings, but to my tags (<span class = "anchor-marker"> </span>
).
It will look something like this:
<ul>
<li><a href="#1">paragraph 1</a></li>
<li><a href="#2">paragraph 2</a></li>
<li><a href="#3">paragraph 3</a></li>
</ul>
<span class="anchor-marker" id="1">
</span>
<span class="anchor-marker" id="2">
</span>
<span class="anchor-marker" id="3">
</span>
How to do it?
How are you creating the <span>
elements? Are these part of your content file, in a template, or in a shortcode?
1 Like
while I see like this:
I will create a shortcode for the headings. Shortcode will contain the <h1 - h6>, and inside span with id.
The only thing I need is that the TOC leads to my spans, and not to the heading.
There are several ways to cheat the system, using the built-in .TableOfContents
. But I think you are better off rolling your own.
markdown
{{< span id="foo" title="The First Span" >}}
This text is **bold**.
{{< /span >}}
{{< span id="bar" title="The Second Span" >}}
This text is _emphasized_.
{{< /span >}}
layouts/shortcodes/span.html
{{ $msg := "The %s shortcode requires two named parameters, id and title. See %s" }}
{{ with $id := .Get "id"}}
{{ with $title := ($.Get "title") }}
{{- $inner := trim $.Inner "\n" -}}
{{- $id := $id | anchorize -}}
<span id="{{ $id }}" data-toc="" data-title="{{ $title }}">{{ $inner | $.Page.RenderString }}</span>
{{ else }}
{{ errorf $msg $.Name $.Position }}
{{ end }}
{{ else }}
{{ errorf $msg $.Name $.Position }}
{{ end }}
layouts/_default/single.html
{{ define "main" }}
{{ .Title }}
{{ $toc := slice }}
{{ $spans := findRE `<span.*data-toc.*?>` .Content }}
{{ range $spans }}
{{ $id := replaceRE `.*id="(.*?)".*` "$1" . }}
{{ $title := replaceRE `.*data-title="(.*?)".*` "$1" . }}
{{ $toc = $toc | append (dict "id" $id "title" $title) }}
{{ end }}
<nav id="TableOfContents">
<ul>
{{ range $toc }}
<li><a href="#{{ .id }}">{{ .title }}</a></li>
{{ end }}
</ul>
</nav>
{{ .Content }}
{{ end }}
1 Like