Svelte logo

Svelte by Example: Loops & Conditionals

Svelte uses {#each} and {#if} template directives to render lists and conditionally render content.

In this example, we'll render a list of todos and display a message based on the remaining amount of todos.

Use an {#each}…{/each} block to iterate over an array in a template.

Use an {#if}…{/if} block to conditionally render HTML.

Use {:else} and {:else if …} directives to add more conditions.

TodoList.svelte
<script>
  import Todo from './Todo.svelte';

  let todos = [
    { task: "Mow lawn", completed: false },
    { task: "Walk dog", completed: false },
    { task: "Read newspaper", completed: false },
  ];
</script>

{#each todos as todo}
  <Todo {...todo} />
{/each}

{#if todos.length === 0}
  <p>All done!</p>
{:else if todos.length === 1}
  <p>Almost there!</p>
{:else}
  <p>Keep going!</p>
{/if}

The index of the current iteration is also available in {#each}.

TodoList.svelte
{#each todos as todo, index}
  <!-- … -->
{/each}

You may also specify a key in an {#each} block. A key is a unique identifier for a list item. Setting a keys is recommended so Svelte can correctly update the DOM when a list item's index changes.

TodoList.svelte
{#each users as user (user.id)}
  <!-- … -->
{/each}