Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Svelte - non-trivial intermediate variable within each loop

How can I create variables inside Svelte's HTML like in React, or is it not at all how I am supposed to use Svelte. I know the example below is trivial but I'm thinking of a case where I really need some heavy logic for subArray (could not use a one liner)

React

<ul>
  {myArray.map((item) => {
    const subArray = item.items.filter(i = i > 0) // <- how can I have an intermediate variable like this in Svelte?
    return <li>{subArray.map(...)}</li>
  }}
</ul>

Svelte

<ul>
  {#each myArray as item}
    <li>
        {#each <complex-logic> as subItem}
        ...
        {/each}
    </li>
  {/each}
</ul>
like image 997
Greg Forel Avatar asked Mar 06 '26 10:03

Greg Forel


1 Answers

You can use the {@const} directive, which is a recent addition to Svelte. In your use case:

<ul>
  {#each myArray as item}
    {@const subArray = item.items.filter(i => i > 0)}
    <li>
        {#each subArray as subItem}
        ...
        {/each}
    </li>
  {/each}
</ul>
like image 76
Thomas Hennes Avatar answered Mar 09 '26 22:03

Thomas Hennes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!