Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write Helpers in HTMLBars?

After the latest release of EmberJS v1.9.0 I am trying to move from Handlebars to HTMLbars. What I am finding very challenging is lack of documentation.

I am trying to implement very simple helpers.

For example take this handlebars helpers:

HTML

<div id="main"></div>

<script type="text/x-handlebars" data-template-name="index">
    {{logIt test}}
    <h1>{{test}}</h1>
</script>

JS

App = Ember.Application.create({
    rootElement: '#main'
});

    App.IndexRoute = Ember.Route.extend({
        setupController: function(controller){
            controller.set('test', 'mytest');
        }
    });

    Ember.Handlebars.registerHelper("logIt", function(something) {
        console.log(something);
    });

Js Fiddle: http://jsfiddle.net/sisir/p463q2L8/

How do I convert it to htmlbars?

like image 925
Sisir Avatar asked Feb 20 '15 08:02

Sisir


3 Answers

As of Ember 1.13, there are two APIs: http://emberjs.com/blog/2015/06/12/ember-1-13-0-released.html#toc_new-ember-js-helper-api

The simplest and more common syntax is now this:

export default Ember.Helper.helper(function(params, hash) {
  return params.join(' ');
});

Helpers receive two arguments: params are the ordered params passed to a helper, and hash contains the key-value options, for example title="Mr.".

like image 58
kmiyashiro Avatar answered Nov 20 '22 22:11

kmiyashiro


As of Ember 1.10.0, this question is solved by doing Ember.HTMLBars.makeBoundHelper(theHelperFunction).

Edit: since Ember 1.13.6 (July 31, 2015), using this is flagged as deprecated.

DEPRECATION: Using Ember.HTMLBars._registerHelper is deprecated. Helpers (even dashless ones) are automatically resolved. [deprecation id: ember-htmlbars.register-helper]

like image 41
dashdashzako Avatar answered Nov 20 '22 23:11

dashdashzako


I believe you can just use Ember.Handlebars.helper which is what is in the latest emberjs guides. This jsbin uses htmlbars and it works. This is the helper in the jsbin

AppLogItHelper = Ember.Handlebars.helper("logIt", function(something){
  console.log(something);
});

If you are using ember-cli it will auto generate one for you but that uses Ember.Handlebars.makeBoundHelper which doesn't work in the jsbin but works in my ember-cli app.

like image 1
brg Avatar answered Nov 20 '22 23:11

brg