Named slots

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:

  1. <article class="contact-card">
  2. <h2>
  3. <slot name="name">
  4. <span class="missing">Unknown name</span>
  5. </slot>
  6. </h2>
  7. <div class="address">
  8. <slot name="address">
  9. <span class="missing">Unknown address</span>
  10. </slot>
  11. </div>
  12. <div class="email">
  13. <slot name="email">
  14. <span class="missing">Unknown email</span>
  15. </slot>
  16. </div>
  17. </article>

Then, add elements with corresponding slot="..." attributes inside the <ContactCard> component:

  1. <ContactCard>
  2. <span slot="name">
  3. P. Sherman
  4. </span>
  5. <span slot="address">
  6. 42 Wallaby Way<br>
  7. Sydney
  8. </span>
  9. </ContactCard>