How to pass arbitrary template variables to helper helper?

I repeat a simple array in the template:

{{#each chapter in chapterList}}
  <li>{{ chapter }} {{ test chapter }}</li>
{{/each}}

chatperListhere, say [1, 2, 3, 4, 5]. I created the Handlebars helper:

Ember.Handlebars.registerHelper('test', function(chapter) {
  return this.get('list.selectedChapter') == chapter
    ? 'selected'
    : '';
});

but the variable chapterin the helper function is just the string "chapter". How can I access the actual variable itself?

+3
source share
2 answers

It looks like an error in Ember (still in the latest v1.0) ... you cannot pass the variable to the helper inside #each or get: -

TypeError: Object.defineProperty called on non-object

I just found a workaround using the contents of options.data, but that means you need to quote the object you pass if it is inside #each (note the “color” instead of the color below)

Template:

<ul>
  <li>{{helpme color 'lorry'}}</li>

{{#each color in model}}
  <li>{{helpme 'color' 'lorry'}}</li>
{{/each}}
</ul>

Helper:

Ember.Handlebars.helper('helpme', function (color, vehicle, opts) {
    var str = color;
    if (typeof opts.data.keywords[color] === 'string') {
        str = opts.data.keywords[color];
    }
    return new Ember.Handlebars.SafeString(str + '_' + vehicle);    
});

... . JSFiddle

EDIT: Ember Ember.Handlebars.registerHelper() Ember.Handlebars.helper()

+2

, Ember.Handlebars.registerBoundHelper, Ember.Handlebars.helper.

Ember.Handlebars.helper('test', function(chapter) {
  return this.get('list.selectedChapter') == chapter ? 'selected' : '';
});
+1

All Articles