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}" rel="noreferrer">
{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}" rel="noreferrer">
{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
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
›
⌄
⌄
⌄
⌄
⌄
<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 target="_blank" href="https://www.youtube.com/watch?v={cat.id}" rel="noreferrer">
{cat.name}
</a>
</li>
<!-- close each block -->
</ul>
loading Svelte compiler...
99
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
›
⌄
⌄
⌄
⌄
⌄
⌄
⌄
⌄
⌄
⌄
⌄
/* App.svelte generated by Svelte v4.2.19 */
import {
SvelteComponent,
append,
attr,
detach,
element,
init,
insert,
noop,
safe_not_equal,
space,
text
} from "svelte/internal";
import "svelte/internal/disclose-version";
function create_fragment(ctx) {
let h1;
let t1;
let ul;
let li;
let a;
let t2_value = cat.name + "";
let t2;
let a_href_value;
return {
c() {
h1 = element("h1");
h1.textContent = "The Famous Cats of YouTube";
t1 = space();
ul = element("ul");
li = element("li");
a = element("a");
t2 = text(t2_value);
attr(a, "target", "_blank");
attr(a, "href", a_href_value = "https://www.youtube.com/watch?v=" + cat.id);
attr(a, "rel", "noreferrer");
},
m(target, anchor) {
insert(target, h1, anchor);
insert(target, t1, anchor);
insert(target, ul, anchor);
append(ul, li);
append(li, a);
append(a, t2);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) {
detach(h1);
detach(t1);
detach(ul);
}
}
};
}
function instance($$self) {
let cats = [
{ id: 'J---aiyznGQ', name: 'Keyboard Cat' },
{ id: 'z_AbfPXTKms', name: 'Maru' },
{
id: 'OUtn3pvWmpg',
name: 'Henri The Existential Cat'
}
];
return [];
}
class App extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance, create_fragment, safe_not_equal, {});
}
}
export default App;
result = svelte.compile(source, {
generate:
css:
});9
1
›
/* Add a <style> tag to see compiled CSS */