sveltesveltekitsvelte-5

passing children's layout.ts data to parent's layout.svelte


So I have been working on the implementation of breadcrumbs feature in my sveltekit webapp.

  1. The idea is, the breadcrumb will be rendering at the most top layout.svelte.
  2. And then the proceeding descendants will somehow pass their breadcrumb data of itself to the parent.
  3. This is helpful when I have a [...rest] route somewhere.
  4. I managed to get it working. But i feel like there might be some better way to handle this.
  5. working example -> [https://stackblitz.com/edit/sveltejs-kit-template-default-2o46jwja?file=src%2Froutes%2Ffolders%2F%5B...rest%5D%2F%2Bpage.svelte][1]
  6. As you can see, im doing it using vanilla js. so the store is not reactive, since I iniatilized it in layout.ts. Meaning it will not be useful in storing reactive data later on.

Would be nice if someone can share their experiences if they encountered something similar like this.


Solution

  • This could probably be approach similarly to passing snippets to a parent layout:
    By setting an object in a context that descendants can write to.

    The pages then do not render content directly but set the breadcrumb data and their content (in form of a snippet) in this context. The parent layout renders children first to get the data, then renders the content from the context/the breadcrumbs.

    Example relating to snippets can be found in this answer.

    This is a bit if a hack, so not ideal. Some of this logic could also be extracted to components but that is probably only marginally better.