2

Imagine I have an Ember component which for purposes of this question merely wraps its content in a div, adding a bit of text:

<div class="Component">
  Value is: {{yield}}
<div>

So I call it as

{{#component}}
  {{model.text}}
{{/component}}

And all is fine. However, if model.text is empty/null/undefined, I don't want to generate the <div class="Component"> part at all. How can I do that? Of course I could do

{{#if model.text}}
  {{#component}}
    {{model.text}}
  {{/component}}
{{/if}}

but that somehow seems duplicative.

What I would really like to do is to be able to define the component as the equivalent of

{{if yield}} {{! made-up syntax; of course it doesn't work }}
  <div class="Component">
    Value is: {{yield}}
  <div>
{{/if}}

Or, alternatively in component.js

yieldNotEmpty: Ember.computed.bool('yield') // made-up syntax; doesn't work

and then in the template.hbs for the component

{{if yieldNotEmpty}}
  <div class="Component">
    Value is: {{yield}}
  <div>
{{/if}}

Any thoughts on how to handle this case?

  • components should have a `-` in the name so they will be compatible with html components in the future. – albertjan Apr 20 '15 at 18:33

2 Answers2

5

As of Ember 1.13.0, a new template word hasBlock is introduced. hasBlock will be true when a component is invoked in block form. For example:

{{#if hasBlock}}
    {{! yield }}
{{else}}
    {{! regular component }}
{{/if}}

So for your example, this would give:

{{#if hasBlock}}
    <div class="Component">
        Value is: {{yield}}
    <div>
{{/if}}

Another keyword introduced is hasBlockParams and it will be true if the component is invoked with block params (invoke in block form with as |someParam|).

nem035
  • 34,790
  • 6
  • 87
  • 99
0

You could shorten your if statement by:

// component template
{{#if showContent}}
    <div class="Component">
        Value is: {{yield}}
    </div>
{{/if}}

// some other template
{{#component showContent=model.text}}
    {{model.text}}
{{/component}}

The downside is though that the component will always create a div element, even if it has no content. So for me it seems that your if statement around your component is the better solution even if it adds some boilerplate code.

jcbvm
  • 1,640
  • 1
  • 15
  • 22
  • Yes, thanks, I considered that, and it does streamline things a bit, but somehow it feels wrong to have to specify it twice like that. –  Apr 20 '15 at 16:39