Part 1 / Logic / Each blocks
If you need to loop over lists of data, use an each
block:
<ul>
{#each cats as cat}
<li>
<a href="https://www.youtube.com/watch?v={cat.id}">
{cat.name}
</a>
</li>
{/each}
</ul>
The expression (
cats
, in this case) can be any array or array-like object (i.e. it has alength
property). You can loop over generic iterables witheach [...iterable]
.
You can get the current index as a second argument, like so:
{#each cats as cat, i}
<li>
<a href="https://www.youtube.com/watch?v={cat.id}">
{i + 1}: {cat.name}
</a>
</li>
{/each}
If you prefer, you can use destructuring — each cats as { id, name }
— and replace cat.id
and cat.name
with id
and name
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<script>
let cats = [
{
id: 'J---aiyznGQ',
name: 'Keyboard Cat'
},
{
id: 'z_AbfPXTKms',
name: 'Maru'
},
{
id: 'OUtn3pvWmpg',
name: 'Henri The Existential Cat'
}
];
</script>
<h1>The Famous Cats of YouTube</h1>
<ul>
<!-- open each block -->
<li>
<a href="https://www.youtube.com/watch?v={cat.id}">
{cat.name}
</a>
</li>
<!-- close each block -->
</ul>
initialising