{#for}

{#for album in albums} repeats its body once for each item in a list. Two more forms:

  • An index: {#for track in tracks, i} names the position too, counting from 0.
  • A range: {#for 1...5, n} counts from 1 to 5 with no list at all.

Puzzle keys each row so it can move, add and remove rows without rebuilding the rest. A store record keys itself by its primary key, and a plain object by its id. Anything else, like a plain string, has nothing to key by, and the dev build says so in the console:

[puzzle] {#for} item (String) has no usable key (no primary key / .id) — falling back to positional diffing; add key={ … } to the row root.

Give such rows a key: any value that is stable and unique among them.

The shop now lists its genres above the grid, worked out in data() from the albums, and the console under the preview shows that warning.

Your turn

  1. In Shop.pzl, add key={ g } to the genre chip, and reload the preview: the warning is gone.
  2. In Album.pzl, number the tracks: change the loop to {#for track in tracks, i} and print { i + 1 } in a <span class="num"> at the start of each row.
  3. Still in Album.pzl, draw the album's rating as five dots under the artist, filled up to album.rating:
<span class="dots" aria-label="Rated { album.rating } out of 5">
  {#for 1...5, n}
    <span class="dot {#if n <= album.rating}is-on{/if}"></span>
  {/for}
</span>

Chapters