8

Is it possible to break iteration in Svelte or limit like in angular (ng-repeat="items in item | limitTo:4")? For example:

{#each items as item, i}
  ...
  {#if i > 4}
    {:break}  <--- break here
  {/if}
  ...
{/each}

3 Answers 3

18

Svelte currently has no special syntax for breaks or ranges. (here's a pending proposal) A common idiom is to use a {length: N} object as the #each parameter, which usually performs better than creating new arrays every render.

{#each {length: 4} as _, i} {items[i]} {/each}

Here are some other patterns that work:

<script>
    let items = ['a', 'b', 'c', 'd', 'e'];
    $: filteredItems = items.slice(0, 4);
    const filterItems = (i) => i.slice(0, 4);
</script>

<div>
    {#each {length: 4} as _, i}
        {items[i]}
    {/each}
</div>
<div>
    {#each items.slice(0, 4) as item}
        {item}
    {/each}
</div>
<div>
    {#each filteredItems as item}
        {item}
    {/each}
</div>
<div>
    {#each filterItems(items) as item}
        {item}
    {/each}
</div>
0
15

There is no {:break} block, but you could slice out the first 4 elements in the array before you iterate over it.

{#each items.slice(0, 4) as item, i} ... {/each}
1

I just use a {#each myItems as item}{#if yourtruevalue} {item} {/if} {/each} I don't know about the performance impact but it's very simple. if yourtruevalue is true - whatever the condition is for the item to render - it will render, and skip the item if not.

Not the answer you're looking for? Browse other questions tagged or ask your own question.