Inside +page.ts and +layout.ts SvelteKit provides parent function to access the data returned from a parent load function, a couple of things to notice when using the parent function.
Load function#
SvelteKit handles data loading for page component (+page.svelte) inside +page.ts (or +page.js) file, exporting a load function in which and the returned value will be available through data prop inside page:
// src/routes/note/[slug]/+page.ts
import type { PageLoad } from './$types'
export const load: PageLoad = function(({ params }) {
return {
note: {
title: `Title for ${params.slug} goes here`,
content: `Content for ${params.slug} goes here`
}
}
})
<!-- src/routes/note/[slug]/+page.svelte -->
<script lang="ts">
import type { PageLoad } from './$types'
export let data: PageLoad
</script>
<h1>{data.note.title}</h1><div>{@html data.note.content}</div>
Using Parent data#
Sometimes it might be useful for a load function to use data from a parent load function. For example, a parent /project/+page.ts routes return a list of tags and their amount to the project list page. Inside each project /project/[slug]/+page.ts we might also need to access this same information, this is where parent function is useful:
// src/routes/+layout.ts
import type { LayoutLoad } from './$types'
export const load: LayoutLoad = function () {
return { a: 1 }
}
///src/routes/abc/+layout.ts
import type { LayoutLoad } from './$types'
export const load: LayoutLoad = async function ({ parent }) {
const { a } = await parent()
return { b: a + 1 }
}
//src/routes/abc/+page.ts
import type { PageLoad } from './$types'
export const load: PageLoad = async function ({ parent }) {
const { a, b } = await parent()
return { c: a + b }
}
Things to notice#
- The
loadfunciton inside+page.tswill receive the merged data from both parent+page.tsand+layout.tsand the sibling+layout.ts, not just the parent. - The
loadfunction inside+layout.tswill receive the merged data from its parentloadin+page.tsand+layout.ts. - A missing
+layout.tsis treated as({ data }) => data. - The
loadfunciton inside+page.server.tsand+layout.server.tswill receive data from only parent+layout.server.ts