Table of contents for Kirby 3

Hello everyone, I need to create a simple table of content based in the headings on a text field. Any one has an experience with this in kirby 3?

I tried with the plugin mentioned here Kirby TOC - Table of contents but is not working on kirby 3.

Thanks!

You can use this field method as a starting point: https://github.com/getkirby/getkirby.com/blob/1bb7a4b42b787066e22e9eb8c21699b9e69c723e/site/plugins/site/fieldMethods.php#L31

On the getkirby.com website we use a snippet that gets the headlines via this method.

You can either do it in the same way, with rendering a snippet in your templates, or, if you prefer using a Kirbytag, create a toc Kirbytags using the method.

Hi @texnixe I will check what you said. Thanks a lot!

Not tested but this may also work.

Depends on what you need, if it’s just one level of headlines like on the getkirby.com website, you don’t need a library but just a few lines of code.

For multiple levels of H-tags, the solution I suggested above won’t work.

Thank you both! I’m “extending” the field method that @texnixe suggested to support different levels and I think it might work.

Maybe a bit late, but I just converted my old Kirby TOC plugin to an independent class. It will work as a starting point for a Kirby plugin, but can also work without Kirby.

Beta

It will work with multiple heading levels.

$toc = new TOC();
$text = $toc->anchorHeadings($text);

echo $toc->list($text); ?>
echo $text;

Thanks! I managed to solve it following @texnixe suggestion. But for sure your solution is going to be useful for others.

How do I implement this into a usable KirbyTag?
I can’t seem to work it out.

EDIT: Have figured it out.

Hi Guido Ferreyra,

Would you mind sharing your implementation? Can’t figure out how to make it work.
Would be much appreciated!

EDIT: Have figured it out.

For anyone interested I’ve updated my repo with changed syntax, much simpler, improved performance and added docs.

$toc = new PHPTableOfContents($html);

// Output the table of contents
echo $toc->list();

// Output the content
echo $toc->html();