Yielding Blocks

Default and Named Blocks With the yield Helper

Yielding Blocks

A component exposes default and named blocks for parents to fill in, optionally passing data out for the parent to bind.

4 min read Level 2/5 #ember#components#blocks
What you'll learn
  • Use the yield helper for the default block
  • Use `{{yield to="name"}}` for named blocks
  • Yield data with `{{yield this.api}}`

A Glimmer component can yield its body back to the caller. This lets parents inject markup into specific spots without prop drilling.

Default Block

{{! my-card.hbs }}
<article class="card">
  {{yield}}
</article>
<MyCard>
  Anything in here lands inside the article.
</MyCard>

Named Blocks

For multiple slots, give each a name with {{yield to="..."}}. The parent fills them with <:name> blocks:

{{! my-card.hbs }}
<article>
  <header>{{yield to="header"}}</header>
  <main>{{yield}}</main>
  <footer>{{yield to="footer"}}</footer>
</article>
<MyCard>
  <:header><h2>Hello</h2></:header>
  <:default>Body content</:default>
  <:footer>Saved 1m ago</:footer>
</MyCard>

Yielding Data

Pass values out to the block — the parent destructures with as |...|:

{{! my-list.hbs }}
{{#each @items as |item|}}
  {{yield item}}
{{/each}}
<MyList @items={{this.posts}} as |post|>
  <h3>{{post.title}}</h3>
</MyList>

has-block

You can check whether the parent provided a given block:

{{#if (has-block "header")}}
  <header>{{yield to="header"}}</header>
{{/if}}
Contextual Components →