plentico / pico

Svelte-like reactive UI compiler written in Go
2 stars 0 forks source link

Loops #14

Open jimafisk opened 10 months ago

jimafisk commented 10 months ago

Just brainstorming some ideas for iterating through items in templates...

Svelte uses each
```svelte
    {#each items as item}
  • {item}
  • {/each}
``` _I like the simplicity of `#each` but it introduces a new non-standard construct that's not quite a [forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)._
Astro uses map
```astro
    {items.map(item =>
  • {item}
  • )}
``` _I like that it uses js-standard [array map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map), but I miss the separation of an opening and closing block_

I was thinking about taking a slightly different approach and leveraging for of. The syntax for this could look like:

<ul>
  {for (const item of items)}
    <li>{item}</li>
  {/for}
</ul>

If you wanted to get the index for the current iteration you would do something like:

<ul>
  {for (let [index, item] of items.entries())}
    <li>{index} - {item}</li>
  {/for}
</ul>

For iterating over Objects you could use Object.entries() (similar to Svelte):

<ul>
  {for (const [key, value] of Object.entries(items))}
    <li>{key} - {value}</li>
  {/for}
</ul>

Or potentially we could even support for in as well:

<ul>
  {for (let key in items)}
    <li>{items[key]}</li>
  {/for}
</ul>