If you need to loop over lists of data, use an each
block:
<ul>
{#each cats as cat}
<li><a target="_blank" 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 target="_blank" 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
.
App.svelte
xxxxxxxxxx
17
1
<script>
2
let cats = [
3
{ id: 'J---aiyznGQ', name: 'Keyboard Cat' },
4
{ id: 'z_AbfPXTKms', name: 'Maru' },
5
{ id: 'OUtn3pvWmpg', name: 'Henri The Existential Cat' }
6
];
7
</script>
8
9
<h1>The Famous Cats of YouTube</h1>
10
11
<ul>
12
<!-- open each block -->
13
<li><a target="_blank" href="https://www.youtube.com/watch?v={cat.id}">
14
{cat.name}
15
</a></li>
'cat' is not defined (13:64)
'cat' is not defined (14:4)
Console
cat is not defined
xxxxxxxxxx
77
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
append,
5
attr,
6
detach,
7
element,
8
init,
9
insert,
10
noop,
11
safe_not_equal,
12
space,
13
text
14
} from "svelte/internal";
15
16
function create_fragment(ctx) {
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */
xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */