Is there a way to tell if a yielded component's has-block is empty?

Viewed 545

I am trying to make a contextual component that can provide a default header when one is not passed in the yielded block. Normally, I could use the has-block helper to tell if a component has block content but this component will always have block content. I think what I need is a way to tell if the yielded component has block content. For example:

{{! panel.hbs }}
<header>
  {{yield header=(component "blank-template")}}
  {{#if (yieldedHeaderEmpty)}}
    <h1>My Default Header</h1>
  {{/if}}
</header>
<section>
  {{yield body=(component "blank-template")}}
</section>
<footer>
  {{yield footer=(component "blank-template")}}
</footer>

I only want the default header to show when the yielded "header" section is empty. I could create a header component which then could use the has-block like so:

 {{! panel.hbs }}
    <header>
      {{yield header=(component "my-header")}}
    </header>
...



 {{! MyHeader.hbs}}
     {{#if (has-block)}}
          {{yield}}
     {{else}}
         <h1>My Default</h1>
     {{/if}}

Functionally I think this will work but the only purpose of the "my-header" component would be for this "panel" component and seems wasteful. Open to ideas. Thanks!

1 Answers

Ember core recently accepted an RFC for "named blocks" which is designed exactly for this purpose. https://github.com/emberjs/rfcs/pull/460. With this feature, we can name the yieldable blocks and access them with their names, like:

template.hbs:

<Panel>
  <:header>This is a customized header</:header>
</Panel>

panel.hbs:

{{#if (has-block "header")}}
  {{yield to="header"}}
{{else}}
  <header> This is the default header </header>
{{/if}}

This is yet to be landed in the Ember core. Luckily we have an official polyfill that supports this feature from 3.12.4: https://github.com/ember-polyfills/ember-named-blocks-polyfill

Related