0
0
Svelteframework~5 mins

Each blocks ({#each}) in Svelte

Choose your learning style9 modes available
Introduction

Each blocks let you show a list of items easily. They repeat a part of your page for every item in a list.

You want to show a list of names or things on your page.
You need to create a menu with many options from an array.
You want to display multiple cards or boxes with similar content.
You want to loop over data from a server and show it in your app.
Syntax
Svelte
{#each items as item}
  <!-- content using {item} -->
{/each}
You can use any variable name instead of item to represent each element.
You can also get the index of each item by adding , index after the item name.
Examples
This shows each fruit in the fruits list inside a paragraph.
Svelte
{#each fruits as fruit}
  <p>{fruit}</p>
{/each}
This shows each user's name with their number in the list.
Svelte
{#each users as user, i}
  <p>{i + 1}. {user.name}</p>
{/each}
This uses a key (number) to help Svelte track items when the list changes.
Svelte
{#each numbers as number (number)}
  <p>{number}</p>
{/each}
Sample Program

This Svelte component shows a list of colors with their position number. It uses an each block to repeat the list items.

Svelte
<script>
  let colors = ['Red', 'Green', 'Blue'];
</script>

<ul>
  {#each colors as color, index}
    <li>{index + 1}: {color}</li>
  {/each}
</ul>
OutputSuccess
Important Notes

Always close the each block with {/each}.

Using keys in each blocks helps Svelte update the list efficiently when items change.

You can nest each blocks inside each other for lists of lists.

Summary

Each blocks repeat content for every item in a list.

You can access the item and its index inside the block.

Keys help Svelte track list items for better updates.