Search code examples
sveltesapper

Slot prop within _layout.svelte not passing prop


I'm working on a Sapper project and I'd like to load in some async data into the layout before loading in the slots. I've found that within a _layout.svelte file, I'm unable to pass props to the slot.

//_layout.svelte
<slot foo={"hello"}></slot>

//index.svelte
<script>
  export let foo;
  alert(foo); // returns undefined
</script>

Has anyone run into this? I imagine I could work around it by just loading in all the data I need on every slot/subpage. The only way I'm able to set a slot prop is by accessing it manually.

$$props.$$scope.ctx.level1.props.foo = "hello"

Solution

  • Passing data like this doesn't seem to work. You can make use of the context though:

    // in _layout.svelte
    import {setContext} from 'svelte';
    setContext('foo', foo);
    
    // in index.svelte
    import {getContext} from 'svelte';
    const foo = getContext('foo');