Skip to main content

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 a length property). You can loop over generic iterables with each [...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
<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...
/* 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:
});
/* Add a <style> tag to see compiled CSS */