Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Ember.Component have both a block and non-block form?

Tags:

I would like to build an Ember.Component that can be used either in block form, or without a block when some default behavior is desired.

For example, in block form:

{{#my-helper}}   ... {{/my-helper}} 

Or non-block form:

{{my-helper}} 

Where the helper template is somehow able to detect that there is not a block and behave accordingly. For example, it would be nice if there was some way to detect the block:

{{#if hasBlock}}   {{yield}} {{else}}   default output {{/if}} 

For my requirements, I need to have some way to output something only if there's not a block.

Any ideas how to do this?

update:

If you're confused by why my question is the same as the accepted answer it's because Ember happened to adopt new syntax that is exactly what I originally imagined up as desirable. When I first asked this question it turned out there was an undocumented way to do this using {{#if template}} but that has since been deprecated with Ember 2.x and there's new syntax {{#if hasBlock}} which happens to match how I phrased my question.

like image 260
Kevin Bullaughey Avatar asked Sep 25 '13 17:09

Kevin Bullaughey


People also ask

What is a component in Ember?

Ember components are used to turn markup text and styles into reusable content. Components consist of two parts: a JavaScript component file that defines behavior, and its accompanying Handlebars template that defines the markup for the component's UI. Components must have at least one dash in their name.

Has ember got a block?

(has-block is a helper which was added intending to replace hasBlock . It is suggested in the guides as best practice but has no API documentation as an Ember helper. (has-block-params is often mentioned by VM developers when (has-block is being discussed, however this is also not documented as a public API.

What does yield do in Ember JS?

The content of the tag is also referred to as the block. The {{yield}} syntax yields to the block once the block is passed into the component. You can think of the Message component like a function, and the block as a callback that you're passing to the component.


2 Answers

Inside the Component you'd want to check the value of hasBlock

{{#if hasBlock}}   {{yield}} {{else}}   <p>Default content for inline (non-block) form of the component.</p> {{/if}} 

Here's a JSBin : http://jsbin.com/IWEKere/1/edit

like image 89
Jeremy Green Avatar answered Sep 24 '22 18:09

Jeremy Green


The link to the docs is here: http://emberjs.com/api/classes/Ember.Component.html#property_template

The docs don't explicitly say that the template attribute is used in this way. Since the Ember.Component class inherits from the Ember.View class, it can be inferred that the component template acts like the Ember.View layout template.

like image 42
benja2729 Avatar answered Sep 23 '22 18:09

benja2729