Learn how to effectively work with loops in Svelte templates to dynamically display data.

Creating Loops

In Svelte templates, you can create loops using the {#each}{/each} syntax. Here’s an example:

<script>
  let goodDogs = ['Roger', 'Syd'];
</script>

{#each goodDogs as goodDog}
  <li>{goodDog}</li>
{/each}

This syntax is similar to what you might have used in other frameworks that use templates.

Getting the Index of Iteration

You can also get the index of the current iteration using the following syntax:

<script>
  let goodDogs = ['Roger', 'Syd'];
</script>

{#each goodDogs as goodDog, index}
  <li>{index}: {goodDog}</li>
{/each}

Note that indexes start at 0.

Identifiers in Lists

When dynamically editing lists by removing or adding elements, it’s recommended to pass an identifier to prevent any issues. You can do so using the following syntax:

<script>
  let goodDogs = ['Roger', 'Syd'];
</script>

{#each goodDogs as goodDog (goodDog)}
  <li>{goodDog}</li>
{/each}

<!-- with the index -->
{#each goodDogs as goodDog, index (goodDog)}
  <li>{goodDog}</li>
{/each}

You can also pass an object, but if your list has a unique identifier for each element, it’s best to use it:

<script>
  let goodDogs = [
    { id: 1, name: 'Roger' },
    { id: 2, name: 'Syd' }
  ];
</script>

{#each goodDogs as goodDog (goodDog.id)}
  <li>{goodDog.name}</li>
{/each}

<!-- with the index -->
{#each goodDogs as goodDog, index (goodDog.id)}
  <li>{goodDog.name}</li>
{/each}

That’s it! Now you have a better understanding of how to work with loops in Svelte templates.