2
votes

I'm trying to write a custom Ember handlebars helper that will return some HTML, but I can't access the block contents within the helper.

Template:

{{#link}}
This is the block content
{{/link}}

Helper:

Ember.Handlebars.registerHelper('link', function (options) {
  var result = '<a href="http://example.com/">'
              + options.fn(this)
              + '</a>';
  return new Handlebars.SafeString(result);
});

The result I'm expecting is: <a href="http://example.com/">This is the block content</a>

Instead I get: This is the block content <a href="http://example.com/">undefined</a>

Fiddle: http://jsfiddle.net/NQKvy/676/

What am I doing wrong?

2

2 Answers

1
votes

I'm not sure it is currently possible to use block helpers in Ember.Handlebars easily. However, you could use a 'regular' Handlebars helpers like so:

{{link "This is the block content" url="http://www.example.com"}}

Helper:

Ember.Handlebars.registerHelper('link', function (value, options) {
    var result = '<a href="'+options.hash.url+'">'
                  + value
                  + '</a>';
    return new Handlebars.SafeString(result);
});

See this jsFiddle.

1
votes

@chopper had the correct answer on how to do what it is you are looking for. However, I just wanted to touch on the issue of Block Helpers to clear up their meaning.

Block helpers are used to determine rendering patterns of a block. They are not "wrapping" helpers.

For example, a Block Helper you're undoubtedly familiar with is a simple {{#if}} helper. This helper intakes a conditional, and uses that to either output the information contained within it, or not. But it doesn't append information before/after the blocked section.

A more complex block helper would be the {{#each}} helper. The each helper will iterate through a set and, by repeatedly calling options.fn(arrayItem), it will render the block multiple times, on each iteration inputting new data into the designated handlebar tags. But those tags are necessary in order to input information.