Skip to main content

Part 3 / Special elements / <svelte:self>

Svelte provides a variety of built-in elements. The first, <svelte:self>, allows a component to contain itself recursively.

It's useful for things like this folder tree view, where folders can contain other folders. In Folder.svelte we want to be able to do this...

{#if file.files}
	<Folder {...file}/>
{:else}
	<File {...file}/>
{/if}

...but that's impossible, because a module can't import itself. Instead, we use <svelte:self>:

{#if file.files}
	<svelte:self {...file}/>
{:else}
	<File {...file}/>
{/if}

Next: <svelte:component>

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
<script>
	import Folder from './Folder.svelte';
 
	let root = [
		{
			name: 'Important work stuff',
			files: [{ name: 'quarterly-results.xlsx' }]
		},
		{
			name: 'Animal GIFs',
			files: [
				{
					name: 'Dogs',
					files: [
						{ name: 'treadmill.gif' },
						{ name: 'rope-jumping.gif' }
					]
				},
				{
					name: 'Goats',
					files: [
						{ name: 'parkour.gif' },
						{ name: 'rampage.gif' }
					]
				},
				{ name: 'cat-roomba.gif' },
				{ name: 'duck-shuffle.gif' },
				{ name: 'monkey-on-a-pig.gif' }
			]
		},
		{ name: 'TODO.md' }
	];
</script>
 
<Folder name="Home" files={root} expanded />
 
initialising