Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
SvelteTemplate syntax

{#snippet ...}

{#snippetname()}...{/snippet}
{#snippetname(param1,param2,paramN)}...{/snippet}

Snippets, andrender tags, are a way to create reusable chunks of markup inside your components. Instead of writing duplicative code likethis...

{#eachimagesasimage}{#ifimage.href}<ahref={image.href}><figure><imgsrc={image.src}alt={image.caption}width={image.width}height={image.height} /><figcaption>{image.caption}</figcaption></figure></a>{:else}<figure><imgsrc={image.src}alt={image.caption}width={image.width}height={image.height} /><figcaption>{image.caption}</figcaption></figure>{/if}{/each}

...you can writethis:

{#snippetfigure(image)}<figure><imgsrc={image.src}alt={image.caption}width={image.width}height={image.height} /><figcaption>{image.caption}</figcaption></figure>{/snippet}{#eachimagesasimage}{#ifimage.href}<ahref={image.href}>{@renderfigure(image)}</a>{:else}{@renderfigure(image)}{/if}{/each}

Like function declarations, snippets can have an arbitrary number of parameters, which can have default values, and you can destructure each parameter. You cannot use rest parameters, however.

Snippet scope

Snippets can be declared anywhere inside your component. They can reference values declared outside themselves, for example in the<script> tag or in{#each ...} blocks (demo)...

<script>let{ message=`it's great to see you!`}=$props();</script>{#snippethello(name)}<p>hello {name}! {message}!</p>{/snippet}{@renderhello('alice')}{@renderhello('bob')}

...and they are ‘visible’ to everything in the same lexical scope (i.e. siblings, and children of those siblings):

<div>{#snippetx()}{#snippety()}...{/snippet}<!-- this is fine -->{@rendery()}{/snippet}<!-- this will error, as `y` is not in scope -->{@rendery()}</div><!-- this will also error, as `x` is not in scope -->{@renderx()}

Snippets can reference themselves and each other (demo):

{#snippetblastoff()}<span>🚀</span>{/snippet}{#snippetcountdown(n)}{#ifn>0}<span>{n}...</span>{@rendercountdown(n-1)}{:else}{@renderblastoff()}{/if}{/snippet}{@rendercountdown(10)}

Passing snippets to components

Explicit props

Within the template, snippets are values just like any other. As such, they can be passed to components as props (demo):

<script>importTablefrom'./Table.svelte';constfruits=[{ name:'apples',qty:5,price:2},{ name:'bananas',qty:10,price:1},{ name:'cherries',qty:20,price:0.5}];</script>{#snippetheader()}<th>fruit</th><th>qty</th><th>price</th><th>total</th>{/snippet}{#snippetrow(d)}<td>{d.name}</td><td>{d.qty}</td><td>{d.price}</td><td>{d.qty*d.price}</td>{/snippet}<Tabledata={fruits}{header}{row}/>

Think about it like passing content instead of data to a component. The concept is similar to slots in web components.

Implicit props

As an authoring convenience, snippets declared directlyinside a component implicitly become propson the component (demo):

<!-- this is semantically the same as the above --><Tabledata={fruits}>{#snippetheader()}<th>fruit</th><th>qty</th><th>price</th><th>total</th>{/snippet}{#snippetrow(d)}<td>{d.name}</td><td>{d.qty}</td><td>{d.price}</td><td>{d.qty*d.price}</td>{/snippet}</Table>

Implicit children snippet

Any content inside the component tags that isnot a snippet declaration implicitly becomes part of thechildren snippet (demo):

App
<Button>click me</Button>
Button
<script>let{ children }=$props();</script><!-- result will be <button>click me</button> --><button>{@renderchildren()}</button>
<scriptlang="ts">let{ children }=$props();</script><!-- result will be <button>click me</button> --><button>{@renderchildren()}</button>

Note that you cannot have a prop calledchildren if you also have content inside the component — for this reason, you should avoid having props with that name

Optional snippet props

You can declare snippet props as being optional. You can either use optional chaining to not render anything if the snippet isn’t set...

<script>let{ children }=$props();</script>{@renderchildren?.()}

...or use an#if block to render fallback content:

<script>let{ children }=$props();</script>{#ifchildren}{@renderchildren()}{:else}fallback content{/if}

Typing snippets

Snippets implement theSnippet interface imported from'svelte':

<scriptlang="ts">importtype{ Snippet }from'svelte';interfaceProps{data:any[];children:Snippet;row:Snippet<[any]>;}let{ data,children,row }:Props=$props();</script>

With this change, red squigglies will appear if you try and use the component without providing adata prop and arow snippet. Notice that the type argument provided toSnippet is a tuple, since snippets can have multiple parameters.

We can tighten things up further by declaring a generic, so thatdata androw refer to the same type:

<scriptlang="ts"generics="T">importtype{ Snippet }from'svelte';let{data,children,row}:{data:T[];children:Snippet;row:Snippet<[T]>;}=$props();</script>

Exporting snippets

Snippets declared at the top level of a.svelte file can be exported from a<script module> for use in other components, provided they don’t reference any declarations in a non-module<script> (whether directly or indirectly, via other snippets) (demo):

<scriptmodule>export{ add };</script>{#snippetadd(a,b)}{a} + {b} = {a+b}{/snippet}

This requires Svelte 5.5.0 or newer

Programmatic snippets

Snippets can be created programmatically with thecreateRawSnippet API. This is intended for advanced use cases.

Snippets and slots

In Svelte 4, content can be passed to components usingslots. Snippets are more powerful and flexible, and as such slots are deprecated in Svelte 5.

Edit this page on GitHub llms.txt


[8]ページ先頭

©2009-2025 Movatter.jp