A Generic way to create a table of content #12316
Replies: 3 comments 4 replies
-
Hello there, the approach I would consider is to utilize Svelte action to automatically collect all relevant heading tags (h2, h3, ...) at runtime when appropriate. For me this is the most minimal solution. And since this should effectively do a full DOM search, it doesn't matter where the headings live, at page level or nested in components. Shameless plug I'm the author of @svelte-put/toc which is a lib that does exactly the above. My hope is to provide a relatively quick setup with sensible defaults, but lots of customization options for flexibility. So far it's been very helpful in my projects that require building Table of Contents. If you are new to Svelte action, I have a blog post here for a very quick introduction. Note Svelte 5 is coming soon and there will be a major release for this |
Beta Was this translation helpful? Give feedback.
-
I do this with context and a component. A benefit of using a component compared to plain elements is the ease of adding additional markup like a My implementation is currently bugged with SSR and hydration (just checked with the latest versions, I tried to isolate but it's possible/likely I have a different issue with hydration), but I'm assuming this should work unless the component initialization order is different between the client and server. I can link the code if you want to see the details. |
Beta Was this translation helpful? Give feedback.
-
melt-ui has a great example of a table of contents component |
Beta Was this translation helpful? Give feedback.
-
Hi,
I'd like to add a table of contents component to all articles pages on my website. Different pages have different ways of displaying their content: some sub-titles are hardcoded in
+page.svelte
, others useMDsveX
, some title are defined at the component levelMyComponentWithH2Tag.svelte
, and some are retrieved at runtime from a database.Regardless of how these pages are structured, I would like to generate a table of contents containing the list of
<h2>
tags present on the page, with anchor links. What is the most robust approach to achieve this?One approach I can think of is to have a global context and append a title and its generated anchor id every time we encounter one using a custom-made
<H2>
component that mimics the native<h2>
. At the end of the page, we can read the context, create a table of contents, and display it where we want using CSS (for instance, if we want to display it before the content).I think this approach would work, but I don't really like replacing all normal
<h2>
tags with a custom-made component. It seems that<svelte:head>
is conceptually similar to what I want to do here, as it allows modifying the head of a page from its body. Could something like that be used to populate a table of contents every time we encounter an HTML tag?Beta Was this translation helpful? Give feedback.
All reactions