Skip to main content
Basic Svelte
Introduction
Reactivity
Props
Logic
Events
Bindings
Classes and styles
Actions
Transitions
Advanced Svelte
Advanced reactivity
Reusing content
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

スニペットを使用すると、別のファイルに抽出することなく、コンポーネント内のコンテンツを再利用できます。

この演習では、三猿の表と、それぞれの Unicode エスケープ シーケンスおよび HTML エンティティを作成します。今のところ、猿は 1 匹だけです。

もちろん、マークアップを複製することもできます。または、{ emoji, description } オブジェクトの配列を作成し、それを {#each ...} ブロックに渡すこともできます。しかし、よりすっきりした解決策は、マークアップを再利用可能なブロックにカプセル化することです。

まず、スニペットを宣言 します。

App
{#snippet monkey()}
	<tr>
		<td>{emoji}</td>
		<td>{description}</td>
		<td>\u{emoji.charCodeAt(0).toString(16)}\u{emoji.charCodeAt(1).toString(16)}</td>
		<td>&amp#{emoji.codePointAt(0)}</td>
	</tr>
{/snippet}

猿はレンダリングするまで見えません。レンダリングしてみましょう。

App
<tbody>
	{#snippet monkey()}...{/snippet}

	{@render monkey()}
</tbody>

残りの猿に対してスニペットを使用する前に、スニペットにデータを渡す必要があります。スニペットには 0 個以上のパラメータを指定できます。

App
<tbody>
	{#snippet monkey(emoji, description)}...{/snippet}

	{@render monkey('🙈', 'see no evil')}
</tbody>

必要に応じて、デストラクチャパラメータを使用することもできます。

残りの猿を追加します。

  • '🙈', 'see no evil'
  • '🙉', 'hear no evil'
  • '🙊', 'speak no evil'

最後に、不要になった <script> ブロックを削除します。

App
<script>
	let emoji = '🙈';
	let description = 'see no evil';
</script>
<script lang="ts">
	let emoji = '🙈';
	let description = 'see no evil';
</script>

スニペットはコンポーネント内のどこにでも宣言できますが、関数と同様に、同じ「スコープ」または子スコープ内のレンダリングタグに対してのみ使用できます。

Edit this page on GitHub

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<script>
	let emoji = '🙈';
	let description = 'see no evil';
</script>
 
<table>
	<thead>
		<tr>
			<th>emoji</th>
			<th>description</th>
			<th>unicode escape sequence</th>
			<th>html entity</th>
		</tr>
	</thead>
 
	<tbody>
		<tr>
			<td>{emoji}</td>
			<td>{description}</td>
			<td>\u{emoji.charCodeAt(0).toString(16)}\u{emoji.charCodeAt(1).toString(16)}</td>
			<td>&amp#{emoji.codePointAt(0)}</td>
		</tr>
	</tbody>
</table>
 
<style>
	th, td {
		padding: 0.5em;
	}
 
	td:nth-child(3),
	td:nth-child(4) {
		font-family: monospace;
	}
</style>