Ghost 使用 11ty 时生成无插件生成 TOC 目录

Ghost 使用 11ty 时生成无插件生成 TOC 目录

April 16, 2024
编码 , 分享 ,

分享一段之前和 ChatGPT 沟通得到的代码。

作用为传入一段 HTML 代码,并获取页面内的 H2、H3、H4 标签,组装成固定格式的 html 字符串返回。

const cheerio = require('cheerio');

module.exports = (html) => {
    if (!html) return;

    const $ = cheerio.load(html);
    let toc = "<ul>";
    let currentH2 = null;
    let currentH3 = null;

    let els = $("h2, h3, h4");

    if(els.length == 0) {
        return;
    }

    $("h2, h3, h4").each((i, el) => {
        const tagName = $(el).prop("tagName");
        const id = $(el).attr("id");
        const title = $(el).text();

        if (tagName === "H2") {
            if (currentH2) {
                if (currentH3) {
                    toc += "</ul></li>";
                    currentH3 = null;
                }
                toc += "</ul></li>";
            }
            toc += `<li><a href="#${id}">${title}</a><ul>`;
            currentH2 = id;
        } else if (tagName === "H3") {
            if (currentH3) {
                toc += "</ul></li>";
            }
            toc += `<li><a href="#${id}">${title}</a><ul>`;
            currentH3 = id;
        } else if (tagName === "H4") {
            toc += `<li><a href="#${id}">${title}</a></li>`;
        }
    });

    if (currentH3) {
        toc += "</ul></li>";
    }
    if (currentH2) {
        toc += "</ul></li>";
    }
    toc += "</ul>";

    return toc;
};

加入评论