ページ内目次(ToC)のレンダリング

Methanol はページのコンパイル時に見出しを自動的に抽出し、ctx.page.toc に構造化されたデータとして格納します。

目次データの構造例:

{
	depth: 2,
	id: 'my-heading',
	value: 'My heading',
	children: []
}

シンプルな ToC レンダラーの実装

const Toc = ({ toc }) => {
	if (!toc?.length) return null
	return (
		<nav aria-label="On this page">
			<div>On this page</div>
			<ul>
				{toc.map((item) => (
					<li>
						<a href={`#${item.id}`}>{item.value}</a>
						{item.children?.length ? <Toc toc={item.children} /> : null}
					</li>
				))}
			</ul>
		</nav>
	)
}

export default function PageTemplate({ PageContent, ExtraHead, ctx }) {
	return (
		<>
			<html>
				<head>
					<ExtraHead />
				</head>
				<body>
					<main>
						<PageContent />
					</main>
					<aside>
						<Toc toc={ctx.page.toc} />
					</aside>
				</body>
			</html>
		</>
	)
}

実装のアドバイス