简体   繁体   中英

Calling Handlebars helper programmatically in Ember

One of my components needs to pick a Handlebar helper dynamically based on the provided parameter.

Something like that {{dynamic-output value=value helper=helper}}

Inside the component class I would like to output the value based on the provided helper.

I couldn't find much info on using Handlebars helpers programmatically :(

Basically, if you have a helper called selectBoxOptions the following code can be used within a helper to call that helper:

return Handlebars.helpers.selectBoxOptions(selectedValue, options);

See this blog post for more details: http://www.remwebdevelopment.com/blog/javascript/handlebars-calling-a-helper-function-from-another-helper-231.html

This is pretty easy to do. Here's how:

helperFunctionOne(value){
    //Fill with the data manipulation you want for "helperOne"
}

helperFunctionTwo(value){
    //Fill with the data manipulation you want for "helperTwo"
}

Ember.Handlebars.registerBoundHelper("helperOne", function(value){
    return helperFunctionOne(value);
});

Ember.Handlebars.registerBoundHelper("helperTwo", function(value){
    return helperFunctionTwo(value);
});

Ember.Handlebars.registerBoundHelper("helperDynamic", function(value, type){
    if(type == 1){
        return helperFunctionOne(value);
    else if(type == 2){
        return helperFunctionTwo(value);
    }
});

In the above code, we've set up 2 helper functions and 3 helpers. You can now call each of these helpers as follows:

{{helperOne someValue}}

{{helperTwo someValue}}

{{helperDynamic someValue someType}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM