Children and slots

Props carry values. To pass a component markup, put it between the tags and mark where it goes:

  • <Children/> renders whatever the caller put between the component's tags.
  • <Slot name="title"/> renders only the caller's child marked slot="title".
<!-- Shelf.pzl -->
<puzzle-view>
  <section class="shelf">
    <h2><Slot name="title"/></h2>
    <ul class="grid">
      <Children/>
    </ul>
  </section>
</puzzle-view>
<!-- Shop.pzl -->
<Shelf>
  <span slot="title">Staff picks</span>
  {#for album in picks}
    <AlbumCard album={ album } @add={ add(album) }/>
  {/for}
</Shelf>

The slot attribute must sit on a direct child of the component tag, and is removed from the page. Everything without one is the default content. A marker can also hold a fallback, shown when nothing fills it: <Children><li>Nothing here yet</li></Children>.

Shelf needs no <script> at all. A component without one is pure template, and reads any props by their bare names.

Your turn

  1. In Shelf.pzl, put <Slot name="title"/> in the heading and <Children/> in the list.
  2. In Shop.pzl, import Shelf from ../components/Shelf.pzl and add two shelves under the grid: Staff picks over picks and New in over newest. data() already returns both.

Scroll the preview: two titled shelves, built from the same card.

Chapters