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.

  import Todo from './Todo.svelte';

  let todos = [
    { task: "Mow lawn", completed: false },
    { task: "Walk dog", completed: false },
    { task: "Read newspaper", completed: false },

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

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

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

{#each todos as todo, index}
  <!-- … -->

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.

{#each users as user (}
  <!-- … -->