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 member, index in team.members}
<li>#{index + 1}: {member.name} - {member.age}</li>
{/each}

Each…As

You can also use the alternate syntax each...as

{#each team.members as member}
<li>{member.name} - {member.age}</li>
{/each}
{#each team.members as member, index}
<li>#{index + 1}: {member.name} - {member.age}</li>
{/each}

Else Conditions

You can use an else block with an each loop to handle the case when the collection is empty or doesn’t exist

{#each item in items}
<div class="item">{item.name}</div>
{else}
<div class="empty-state">No items available</div>
{/each}

Special Values

Index

The value index will automatically be added to data context when iterating over arrays

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

Key

The value key will be added to data context when iterating over an object

{#each value, key in obj}
{key} - {obj}
{/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}

Or you can just use regular js expressions

{#each person in team}
{person.name}
Employee #{index + 1})
{/each}

Custom Aliases

You can define a custom variable name for index using a comma after the item name

{#each product, i in products}
<p>Item #{i + 1}: {product.name}</p>
{/each}

This can be useful if you have multiple levels of each loops that need their own index

{#each team, teamIndex in teams}
<h4>{team.name}</h4>
<ul>
{#each member, memberIndex in team.members}
<li>
Team #:{teamIndex + 1} Member #:{memberIndex + 1} <br>
{member.name} - {member.age}
</li>
{/each}
</ul>
{/each}

You can also use custom alises for key

{#each objValue, objKey in someObj}
{objKey} - {objValue}
{/each}

This

When using each without in or as you can use this to refer to the entire 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.