Skip to main content

{#each ...}

{#each expression as name}...{/each}
{#each expression as name, index}...{/each}

Iterating over values can be done with an each block. The values in question can be arrays, array-like objects (i.e. anything with a length property), or iterables like Map and Set. (Internally, they are converted to arrays with Array.from.)

If the value is null or undefined, it is treated the same as an empty array (which will cause else blocks to be rendered, where applicable).

<h1>Shopping list</h1>
<ul>
	{#each items as item}
		<li>{item.name} x {item.qty}</li>
	{/each}
</ul>

each ブロックは インデックス も指定可能で、これは array.map(...) コールバックの第二引数に相当します:

{#each items as item, i}
	<li>{i + 1}: {item.name} x {item.qty}</li>
{/each}

Keyed each blocks

{#each expression as name (key)}...{/each}
{#each expression as name, index (key)}...{/each}

key の式(各リストアイテムを一意に識別できる必要があります)が与えられた場合、Svelte は、データがアイテムの挿入・移動・削除によって変化したとき、リストの末尾にアイテムを追加・削除して途中のアイテムを更新するのではなく、その key を使用して賢くリストを更新します。

key はどんなオブジェクトでもよいですが、そのオブジェクト自体が変更されたときに同一性を維持できるため、文字列か数値を推奨します。

{#each items as item (item.id)}
	<li>{item.name} x {item.qty}</li>
{/each}

<!-- or with additional index value -->
{#each items as item, i (item.id)}
	<li>{i + 1}: {item.name} x {item.qty}</li>
{/each}

each ブロック内では分割代入や残余構文のパターンを自由に使用できます。

{#each items as { id, name, qty }, i (id)}
	<li>{i + 1}: {name} x {qty}</li>
{/each}

{#each objects as { id, ...rest }}
	<li><span>{id}</span><MyComponent {...rest} /></li>
{/each}

{#each items as [id, ...rest]}
	<li><span>{id}</span><MyComponent values={rest} /></li>
{/each}

Each blocks without an item

{#each expression}...{/each}
{#each expression, index}...{/each}

In case you just want to render something n times, you can omit the as part:

<div class="chess-board">
	{#each { length: 8 }, rank}
		{#each { length: 8 }, file}
			<div class:black={(rank + file) % 2 === 1}></div>
		{/each}
	{/each}
</div>

<style>
	.chess-board {
		display: grid;
		grid-template-columns: repeat(8, 1fr);
		rows: repeat(8, 1fr);
		border: 1px solid black;
		aspect-ratio: 1;

		.black {
			background: black;
		}
	}
</style>

Else blocks

{#each expression as name}...{:else}...{/each}

each ブロックは {:else} 節を持つことができ、リストが空の場合にそれがレンダリングされます。

{#each todos as todo}
	<p>{todo.text}</p>
{:else}
	<p>No tasks today!</p>
{/each}

Edit this page on GitHub llms.txt

previous next