Custom Slug Layout in Svelte

- 1 minute read

By adding a __layout.svelte file to a folder in SvelteKit, you can nest a new layout within the parent layout.

This works well for simple file structures, like the following:

src/
  routes/
    example/
      __layout.svelte
      index.svelte
    __layout.svelte
    index.svelte

However, for dynamic slug pages, nesting a new layout is a bit less intuitive.

To add a dynamic slug page, you would normally just create a [slug].svelte file, like this:

src/
  routes/
    example/
      __layout.svelte
      [slug].svelte <-- we want to nest a new layout for this file!
      index.svelte
    __layout.svelte
    index.svelte

However, to add a layout to that slug page, you’ll need to create a folder called [slug], and place your __layout.svelte inside there. The index.svelte file in the slug folder acts as as a [slug].svelte file, but it can be nested within its sibling layout:

src/
  routes/
    example/
      [slug]/
          __layout.svelte <-- our slug page now has its own layout!
          index.svelte
      __layout.svelte
      index.svelte
    __layout.svelte
    index.svelte

Link to this section Conclusion

And that’s how you can customize the layout of a dynamic slug page in SvelteKit!