'SvelteKit: How to Use Named Slots Based on Route

I am fairly new to SvelteKit and can't figure out an issue related to slots. I'm trying to make an app layout that has a master and detail pane where the contents of the master and detail are determined based on the route.

Let's say I have a __layout.svelte file like this:

//-------------------------
// routes/__layout.svelte
//-------------------------
<main>
  <slot name="master" />
  <slot name="detail" />
</main>

Then I have another page like this (with several more route pages that are similar):

//-------------------------
// routes/users.svelte
//-------------------------

<div slot="master">
  Users master content...
</div>

<div slot="detail">
  Users detail content...
</div>

When I navigate to http://localhost:3000/users I just get an error that says I can't use slot="" in users.svelte because it's not inside a child component.

Am I going about this all wrong? How would you pull off a similar app layout in SvelteKit?



Solution 1:[1]

You're almost there, however you can't use named slots in __layout.svelte

That __layout component only receives one (default) slot. That slot contains the component of the matched route.

A solution would be to rename the __layout into a standalone component and use that inside the route.svelte:

//-------------------------
// lib/MasterDetail.svelte
//-------------------------
<main>
  <slot name="master" />
  <slot name="detail" />
</main>
//-------------------------
// routes/users.svelte
//-------------------------
<script>
import MasterDetail from "$lib/MasterDetail.svelte"
</script>

<MasterDetail>
  <div slot="master">
    Users master content...
  </div>

  <div slot="detail">
    Users detail content...
  </div>
</MasterDetail>

Another solution could be to restrict the route.svelte to only render the detail part and let the __layout render the master part.
Maybe look into nested layouts and the page store to detect which detail is active.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bob Fanger