Handlebars passing object into helper

2019-04-08 14:58发布

问题:

Currently I have an Ember object that looks like this:

name: 'Bob'
xs: {
    'actual':50
    'target':55
}

I have around 5-6 fields similar to xs. I need a helper method that can take that xs object and then return whether or not the target has been hit.

I thought of doing this:

Handlebars.registerHelper('hasHitTarget', function(attribute) {
    if (attribute.actual >= attribute.target)
    {
        return block(this);
    }
});

{{#each user in App.userController}}
    {{#hasHitTarget user.xs}}
        Target Hit
    {{/hasHitTarget}}
{{/each}}

Everything I've read online says this should work. But it doesn't. When I console.log(attribute) it returns user.xs as a string. What's going on?

回答1:

There's a difference between Handlebars & Ember.Handlebars, Ember extends Handlebars internally to add extra functionality.

That being said you are using the wrong helper here, you need to use Ember.Handlebars.registerBoundHelper.

Ember.Handlebars.registerBoundHelper('hasHitTarget', function(attribute) {
  if (attribute.actual >= attribute.target) {
    return block(this);
  }
});


回答2:

Passing an object to a Handlebars Helper from within an #each doesn't work as intended, due to a bug in Ember (currently v1.0), there is a workaround though ... see my post here

https://stackoverflow.com/a/18787740/1780102