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?
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.
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-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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With