jdsteinbach / eleventy-plugin-toc

11ty plugin to generate a TOC from page content
61 stars 19 forks source link

Layout.html specific custom anchors #46

Open FrostKiwi opened 8 months ago

FrostKiwi commented 8 months ago

Big fan of this plugin. I use it for the table of contents on my Tech blog https://blog.frost.kiwi/

I have hacked in a feature I need with the implementation of that blog. Source code is here: https://github.com/FrostKiwi/treasurechest

I have a comments section and I want the Post title to be in the table of contents. Both of these are in the layout.html though, not the markdown posts themselves. Eg., here are is the header and anchor for the comments:

<h2 id="comments" class="site_title">Comment via GitHub <a href="#comments" class="anchor-link">#</a></h2>

I need these reflected in the table of contents. I found no feature to insert those, so I hacked in this feature via this function in this line of my .eleventy.js via rather fragile string manipulation.

eleventyConfig.addFilter("modifyTOC", function (tocHtml, postTitle) {
    if (!tocHtml)
        tocHtml = `<nav class="toc"><ul></ul></nav>`;
    /* Clear whitespace before string matching */
    tocHtml = tocHtml.replace(/>\s+</g, '><');
    /* Header */
    tocHtml = tocHtml.replace('<ul>', `<ul><li><a href="#${postTitle}">${postTitle}</a><ul>`);
    /* Comments */
    tocHtml = tocHtml.replace('</ul></nav>', '</ul></li><li><a href="#comments">Comments</a></li></ul></nav>');
    return tocHtml;
});

There is also some extra shenanigans going on with the nesting. I want the H1 Post title and Comments to be the outer most bullet points, with the rest being nested under the title bullet point. However, only the title is H1. All other points and also the comments are H2. So heading level and nesting don't quite correspond.

So this is the feature I needed for my blog: Being able to cross reference custom tags in the layout.html, with a specific placement in the Table of Contents hierarchy. I think it would make a good QoL feature, considering that I have not found such a feature in all the other markdown-it based table of content plugins.