Is it possible to detect post has table of contents?


I want to add toc function to my theme.

The template example in hugo site is:

{{ if and (gt .WordCount 400 ) (ne .Params.toc "false") }}
{{ end }}

But because I am from Wordpress. Lots of previous posts have many words but I do not use any tag.

I want to detect that if the post do not have tag, the toc part will not display.

Is there any way to detect it?

Thanks for reply.

You can do that using isset

If you do:

{{ if .TableOfContents}}
// it has TOC
{{ end }}

You also check the length

{{ if ge (len .TableOfContents) 100 }}
// it has TOC longer than 100 chars
{{ end }}

Also see the with keyword.

At current time, I check parameter for the post
{{ if (.Params.toc) }}

But I want a global site solution

Thanks a lot.
I use
{{ if and (ge (len .TableOfContents) 100) (ne .Params.toc “false”) }}

Work like a charm!

1 Like