Named slots in layout files in sveltekit

A little while ago I found out you can’t use named slot in +layout.svelte files. But there is an alternative way of doing things. Rich Harris, one of the creators of Svelte, has an explaining of why this doesn’t work but also suggested an alternative way that does work.

He’s done a demo which show how it works and can also see it implemented in ELS.

In the +layout.js file, import any components and any data you might need to feed your component.

import type { LayoutLoad } from './$types';
import { base } from '$app/paths';
import { Breadcrumb } from '@onsvisual/svelte-components';

export const load: LayoutLoad = async ({ fetch }) => {
	const coreMetadata = await (await fetch(`${base}/insights/core-metadata.json`)).json();
		coreMetadata,
		title: `Explore local statistics - ONS`,
		description: `Find, compare and visualise statistics about communities in the United Kingdom. Includes data on population, economy and health.`,
		pageType: `home page`,
		component: Breadcrumb,
		breadcrumbLinks: [
			{ label: 'Home', href: 'https://www.ons.gov.uk/', refresh: true },
			{ label: 'Explore local statistics' }
		],
		background: '#e9eff4'
	};
};

Then in the +layout.svelte file, you have access to those components and data. You can use a <svelte:component> to specify the component and then pass through any data to the props for that component.

{#if $page.data.component}
    <svelte:component
        this={$page.data.component}
        links={$page.data.breadcrumbLinks}
        background={$page.data.background ?? ''}
    />
{:else}
    <p>$page.data.component is undefined</p>
{/if}

According to the Github issues thread, this issue is fixed in Svelte5 with fragments.