Astro Repo

Using Astro Content Collections

3 min read

Getting Content Headings from Astro Content Collections

It seems the Astro Content Collections Docs haven’t been updated for this yet, and it took me a bit of time to find this, so I hope this helps someone out there.

The headings object is returned from Astro post.render();

src/pages/blog/[..slug].astro
const post = await Astro.props;

const { Content, headings } = await post.render();

headings Object Variables

beeteedubs:

`code` works on `###` headings in mdx.

slug is just the slug, so you will need to add a #.

depth is the heading depth, ex: <h2></h2> === depth:2.

TableOfContents.astro
---
const { headings } = Astro.props;
---

<ul class='menu' data-toc-list>
  {
    headings.map((h) => {
      if (h.depth < 4)
        return (
          <li>
            <a class={`h-depth--${h.depth}`} href={`#${h.slug}`}>
              {h.text}
            </a>
          </li>
        );
    })
  }
</ul>