How can you find out if a {{yield}} in a component is empty?


#1

I want to display a generic message if the {{yield}} in a component is empty. Is it appropriate to use {{#if yield}} in this case? Or is that an anti-pattern?


#2

has-block, or hasBlock, should do the trick.

{{#unless has-block}}
  no yield supplied message.
{{else}}
  {{yield}}
{{/unless}}

Example: https://ember-twiddle.com/a8aae3ca2dc60d0f2f372282a466a6e2?openFiles=templates.application.hbs%2Ctemplates.components.x-foo.hbs

Edit: looks to be public since it’s covered in the guides. https://guides.emberjs.com/v2.10.0/components/block-params/#toc_supporting-both-block-and-non-block-component-usage-in-one-template


#3

I have tried that but it doesn’t check that it’s empty in 2.10. it just checks that it’s using it as a block style instead of inline


#4

I guess I don’t understand your question.


#5

So I know for a fact that my component will always be used in block form. A la:

{{#my-component-here}} {{/my-component-here}}

However, what I want to find out is if someone used it like so:

{{#my-component-here}} {{some-item-to-render}} {{/my-component-here}}

I want to know if they added something like “some-item-to-render” instead of it being like the first example. The hasBlock will be true on both of those. I need to know if the actual {{yield}} is empty or not.


#6

There is basically no way of knowing that without manually checking the DOM. Even if you check the DOM though, you will have to make annoying/odd decisions. For example, in your example snippet:

{{#my-component-here}}
{{/my-component-here}}

The {{yield}} is in fact not empty (it contains a text node with whitespace).


In general, I would think that requiring folks do:

{{#my-component-here}}
{{/my-component-here}}

When this would have been fine:

{{my-component-here}}

Is a bit odd.

IMO, you should probably refactor so that you can rely on has-block