Count headings in Table of Contents

Is it possible to count the number of headings in the Table of Contents and then add a css class to the markup if the count exceeds a value?

For long pages with many headings, I’d like to add a css class to the markup output so I can break up the TOC into two columns.

The .TableOfContents method renders something like this:

<nav id="TableOfContents">
    <li><a href="#section-1">Section 1</a>
        <li><a href="#section-11">Section 1.1</a></li>

Use the findRE function to count the number of li elements:

{{ .TableOfContents | findRE `<li>` | len }}  --> 2 

@jmooring - thank you

I think I’ll use {{ findRE `(?s)<h2.*?>.*?</h2>` .Content | len }} since I’m really only interested in finding the count for h2.

Wouldn’t <h2 be sufficient as RE in that case? You don’t need groups nor the closing tag, I think.

1 Like