The previous example contained a default slot, which renders the direct children of a component. Sometimes you will need more control over placement, such as with this <ContactCard>
. In those cases, we can use named slots.
In ContactCard.svelte
, add a name
attribute to each slot:
<article class="contact-card">
<h2>
<slot name="name">
<span class="missing">Unknown name</span>
</slot>
</h2>
<div class="address">
<slot name="address">
<span class="missing">Unknown address</span>
</slot>
</div>
<div class="email">
<slot name="email">
<span class="missing">Unknown email</span>
</slot>
</div>
</article>
Then, add elements with corresponding slot="..."
attributes inside the <ContactCard>
component:
<ContactCard>
<span slot="name">
P. Sherman
</span>
<span slot="address">
42 Wallaby Way<br>
Sydney
</span>
</ContactCard>
App.svelte
ContactCard.svelte
xxxxxxxxxx
7
1
<script>
2
import ContactCard from './ContactCard.svelte';
3
</script>
4
5
<ContactCard>
6
<!-- contact details go here -->
7
</ContactCard>
Console
xxxxxxxxxx
59
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
create_component,
5
destroy_component,
6
init,
7
mount_component,
8
safe_not_equal,
9
transition_in,
10
transition_out
11
} from "svelte/internal";
12
13
import ContactCard from "./ContactCard.svelte";
14
15
function create_fragment(ctx) {
16
let contactcard;
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */