Svelte 3 - How to loop each block X amount of times

Viewed 23154

I'm hoping to find a way to iterate over an #each block a set amount of times in Svelte 3. In Vue I would do something like this:

<li v-for="i in 3"><!-- somecontent --></li>

But as I understand Svelte handles loops much differently using the .length property of the array being #eached. Is there some way to pull off something like this in Svelte?

{#each 3 as i}
  <li><!-- somecontent --></li>
{/if}
4 Answers

You can use {#each ...}, like:

{#each Array(3) as _, i}
    <li>{i + 1}</li>
{/each}

An #each tag can loop anything with a length property, so:

{#each {length: 3} as _, i}
    <li>{i + 1}</li>
{/each}

will also work, if you prefer.

i Use like this for travelling from a to b in Svelte

{#each Array.from(Array(b+1).keys()).slice(a) as i }
    <h1>{i}</h1>                    
{/each}

example (1 to 100):

{#each Array.from(Array(100+1).keys()).slice(1) as i }
    <h1>{i}</h1>                    
{/each}

You can use clean variable from the script section (mmm... for a pagination):

// script
export let numOfPages = 10
const pagesArray = Array.from({length: numOfPages}, (x, i) => i+1) // [1,2,3,4,5,6,7,8,9,10]

// template
{#each pagesArray as page}
    <li>{page}</li>
{/each}
Related