Hide TOC if only one heading available

Follow up to this question that was solved by @jmooring . How do I add a condition to hide the box if only one heading (in this case h2) is present in the whole content page?

Adding to the code from your previous related topic, replace .Content in your template with:

{{ if gt ((findRE `(?i)<h2` .Content) | len) 1 }}
  {{ replaceRE `(?s)(.*?)(<h2.*)` (print "$1" .TableOfContents "$2")  .Content | safeHTML }}
{{ else }}
  {{ .Content }}
{{ end }}

Example:

git clone --single-branch -b hugo-forum-topic-42666 https://github.com/jmooring/hugo-testing hugo-forum-topic-42666
cd hugo-forum-topic-42666
hugo server

The solution omits the TOC in pages with one h2 but multiple h3s and h4s. Perhaps I should have been more clear and specify “any heading” in the content. That is–

  1. If the content has only one heading (no matter which level) then do nothing.
  2. But if there is a heading present, insert the TOC before the first h2
{{ if gt ((findRE `(?i)<h/d` .Content) | len) 1 }}
  {{ replaceRE `(?s)(.*?)(<h2.*)` (print "$1" .TableOfContents "$2")  .Content | safeHTML }}
{{ else }}
  {{ .Content }}
{{ end }}

TOC disappears completely with this code. Removing /d it appears.

Sorry. I should have copied and pasted instead of editing previous response. Backslash instead of slash…

{{ if gt ((findRE `(?i)<h\d` .Content) | len) 1 }}
  {{ replaceRE `(?s)(.*?)(<h2.*)` (print "$1" .TableOfContents "$2")  .Content | safeHTML }}
{{ else }}
  {{ .Content }}
{{ end }}
3 Likes

Works now. Many thanks.

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