In the previous post, I've managed to load data from an YAML file into svelte, and prepare for usage in the file where the loading process happened (__layout.svelte
in my case).
What if I need (part of) the data in other files, like index.svelte
?
I can't scope it out, but I can use the stores to make it available.
In __layout.yml
I need to save the data in a store:
<script lang="ts">
import { setContext } from 'svelte';
import { writable } from 'svelte/store';
export let config: any;
// Make config available to pages using the layout
//
const config$ = writable(config);
$: $config$ = config;
setContext('config', config$);
</script>
Now the data is saved.
In index.svelte
I load it:
<script lang="ts">
import { getContext } from 'svelte';
const config$: any = getContext('config');
$: config = $config$;
</script>
Tadaaaa! The configuration data is available in index.svelte
. Easy!
HTH,
Member discussion: