Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handlebar helper inside {{#each}}

I try to call a registered handlebar helper inside a {{#each}} loop. Unfortunately Ember.js complains because it tries to resolve the helper as a property of the controller rather than a helper.

Handlebars.registerHelper('testHelper', function(name) {
    return 'foo: ' + name
});

(names and content are just dummy values to show the example)

{{#each entry in App.testController}}
   <div>{{{testHelper entry.name}}}</div>
{{/each}}

The error that the Ember.js prints is:

Uncaught Error:  Handlebars error: Could not find property 'testHelper' on object <App.testController:ember254>.

How do I need to call the registered helper so that it gets recognized?

like image 511
rit Avatar asked Sep 11 '12 09:09

rit


People also ask

What is helper in Handlebars?

A Handlebars helper call is a simple identifier, followed by zero or more parameters (separated by a space). Each parameter is a Handlebars expression that is evaluated exactly the same way as described above in "Basic Usage": template {{firstname}} {{loud lastname}}

How do I register Handlebars in helpers?

registerHelper("noop", function(options) { return options. fn(this); }); Handlebars always invokes helpers with the current context as this , so you can invoke the block with this to evaluate the block in the current context.

Which built in helper method is the inverse of `# If `?

You can use the unless helper as the inverse of the if helper. Its block will be rendered if the expression returns a falsy value. If looking up license under the current context returns a falsy value, Handlebars will render the warning. Otherwise, it will render nothing.

How do you escape curly braces with Handlebars?

Declare a template in the HTML file. Handlebars expressions are put into double curly braces {{expr}} for HTML-escaped content; otherwise, use triple curly brackets {{{expr}}} to avoid HTML-escaping.


1 Answers

Got it running, either with this solution,

Javascript

Handlebars.registerHelper('testHelper', function(property, options) {
  return 'foo: ' + Ember.get(options.data.view.content, property);
});

Handlebars template

<script type="text/x-handlebars" data-template-name='app-view'>
  <ul>
  {{#each entry in content}}
    <li>{{testHelper name}}</li>
  {{/each}}
  </ul>
</script>​

Or even better, with this one:

Javascript

Handlebars.registerHelper('testHelper', function(property) {
  return 'foo: ' + Ember.get(this, property);
});

Handlebars template

<script type="text/x-handlebars" data-template-name='app-view'>
  <ul>
  {{#each entry in content}}
    {{#with entry}}
      <li>{{testHelper name}}</li>
    {{/with}}
  {{/each}}
  </ul>
</script>​
like image 158
Mike Aski Avatar answered Sep 18 '22 14:09

Mike Aski