user663031
user663031

Reputation:

Ember: control component behavior based on content of 'yield'

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?

Upvotes: 2

Views: 338

Answers (2)

nem035
nem035

Reputation: 35481

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|).

Upvotes: 5

jcbvm
jcbvm

Reputation: 1670

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.

Upvotes: 0

Related Questions