Dynamic headings in tableofContents? #2280
-
Hello, is it possible to add headings based on obiect variable? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
You can’t do this directly in MDX unfortunately — we use Astro’s There are a few alternatives, so it depends a bit exactly where the data object is coming from: Alternative 1: Use a custom page. Using a custom page gives you full control over the table of contents, so you can do something like this: ---
// src/pages/example.astro
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
const sections = [
{ id: 'section-one', heading: 'Section One', content: '...' },
{ id: 'section-two', heading: 'Section Two', content: '...' },
// ...
];
---
<StarlightPage
frontmatter={{ title: 'My custom page' }}
headings={sections.map(section => ({ slug: section.id, text: section.heading, depth: 2 }))}
>
{
sections.map(section => (
<>
<h2 id={section.id}>{section.heading}</h2>
{section.content}
</>
))
}
</StarlightPage> Alternative 2: Use a component override to pass custom data to the table of contents. This approach may be a bit awkward if you only have this requirement for one specific page, but it could work if you have this data available at the right point. There’s one small example of this approach here: #1366 (comment) |
Beta Was this translation helpful? Give feedback.
You can’t do this directly in MDX unfortunately — we use Astro’s
headings
extraction which doesn’t take into account dynamic/component headings.There are a few alternatives, so it depends a bit exactly where the data object is coming from:
Alternative 1: Use a custom page.
Using a custom page gives you full control over the table of contents, so you can do something like this: