Passing Snippet to grandchildren #10709
Replies: 2 comments
-
|
Your current approach using Svelte 5 solution (Snippets + Context):<!-- Render1.svelte -->
<script>
import ParentTemplate from './ParentTemplate.svelte';
</script>
<ParentTemplate>
{#snippet grandchildView()}
<p>Content for Render1</p>
{/snippet}
</ParentTemplate><!-- ParentTemplate.svelte -->
<script>
import { setContext } from 'svelte';
import ChildTemplate from './ChildTemplate.svelte';
let { grandchildView, children } = $props();
// Pass snippet via context so GrandChildTemplate can access it
setContext('grandchildView', grandchildView);
</script>
{@render children?.()}<!-- ChildTemplate.svelte -->
<script>
import GrandChildTemplate from './GrandChildTemplate.svelte';
let { grandChildren } = $props();
</script>
{#each grandChildren as grandChild}
<GrandChildTemplate {grandChild} />
{/each}<!-- GrandChildTemplate.svelte -->
<script>
import { getContext } from 'svelte';
const grandchildView = getContext('grandchildView');
</script>
{@render grandchildView()}Key points:
Svelte 4 equivalent:Use named slots + Your approach is correct — just make sure the snippet is passed as a named snippet prop and not as a regular prop object. Hope this helps! |
Beta Was this translation helpful? Give feedback.
-
|
context is the right approach for passing snippets to grandchildren when you want the template component to stay unaware of the view. using <!-- TemplateModule.svelte -->
<script>
import { setContext } from "svelte";
import { GRANDCHILD_VIEW } from "./context-keys.js";
let { grandchildView } = $props();
setContext(GRANDCHILD_VIEW, grandchildView);
</script><!-- GrandChildTemplate.svelte -->
<script>
import { getContext } from "svelte";
import { GRANDCHILD_VIEW } from "./context-keys.js";
const view = getContext(GRANDCHILD_VIEW);
</script>
{@render view?.()}the alternative without context is render props: pass the snippet as a prop all the way down. context is better here because the intermediate TemplateModule does not need to know about GrandChildTemplate internals. if you are on svelte 5, the snippet is just a function, so |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I have template module (shown below) which should be unaware of any view being fed into it: Render1, Render2, etc. The view in this case is the grandchildView which needs to be passed down to GrandChildTemplate component. I utilise context but wonder if there is a better way to do it without context or passing props all the way down?
I don't mind if it is Svelte4 or Svelte5 solution.
Beta Was this translation helpful? Give feedback.
All reactions