Loops Iterating through collections Guide

Loops

Types of Loops

Each

A basic each loop allows you to access properties of a collection inside the loop directly

{#each people}
{name} - {age}
{/each}

each loops can improve readability of templates in simple use-cases.

{#each todos}
<span class="description">
{description}
</span>
<span class="status">
{maybe completed 'Completed' 'Incomplete'}
</span>
{/each}

Each…In

You can define each item of a loop using each...in syntax.

{#each member in team.members}
<li>{member.name} - {member.age}</li>
{/each}

each...in loops can help make templates more readable when using multiple levels of looping.

{#each team in teams}
<h4>{team.name}</h4>
<ul>
{#each member in team.members}
<li>{member.name} - {member.age}</li>
{/each}
</ul>
{/each}

Special Values

Index

The value @index can be used to get the current loop index.

{#each item in items}
{@index} - {item}
{/each}

This can be used with helpers like numberFromIndex to output non-zero indexed values.

{#each person in team}
{person.name}
Employee #{numberFromIndex @index})
{/each}

This

When looping over values like strings or numbers without the each...in syntax you can use the keyword this to access the value.

{#each numbers}
{this}
{/each}

Using Expressions

Template Instance

Iterables can be the results of expressions, for instance pulling a set of values from your component

{#each item in getVisibleMenu}
{item}
{/each}

Global Helpers

Global helpers can be used to generate iterables like number ranges.

{#each number in range 0 4}
{number}
{/each}

Example

The following example uses loops with snippets to output values into a table.