Just a few weeks until the 2021 JavaScript Full-Stack Bootcamp opens.
Signup to the waiting list!
Svelte templates offer us the fantastic each block that lets us iterate on an array, or anything that is iterable:
<script>
let goodDogs = ['Roger', 'Syd']
</script>
{#each goodDogs as goodDog}
<li>{goodDog}</li>
{/each}
But what if you want to repeat a block for a few times, based on a variable? Let’s say we have the rows
variable that holds a number, and we want to use that as the loop variable.
We can do what we need by creating an array, using the Array(n)
syntax. This will create an array, initializing it with n
items:
{#each Array(rows) as _, row}
{row}
{/each}
Download my free Svelte Handbook
The 2021 JavaScript Full-Stack Bootcamp will start at the end of March 2021. Don't miss this opportunity, signup to the waiting list!
More svelte tutorials:
- Getting started with Svelte - a short tutorial
- How to work with props in Svelte
- How to import components in Svelte
- How to export functions and variables from a Svelte component
- Svelte templates: conditional logic
- How to rerender a Svelte component on demand
- Svelte Slots
- How to add comments in Svelte templates
- Svelte Bindings
- Handling State Updates in Svelte
- Reactive Statements in Svelte
- Svelte Lifecycle Events
- Svelte templates: loops
- Resolve promises in Svelte templates
- Working with events in Svelte
- Cross-component State Management in Svelte
- How to access a URL parameter in Sapper outside of script module
- How to dynamically apply CSS in Svelte
- How to redirect to a URL in Sapper
- How to simulate a for loop in Svelte templates