问题
How can I call a JavaScript function from inside a handlebars script? Reason:
I wasn't able to break the {{#each}} from inside handlebars. So I need to pass it to JavaScript to do the logic.
回答1:
You can do that with helpers;
Handlebars.registerHelper("printItems", function(items) {
var html = "<ul>";
items.forEach(function(entry) {
html += "<li>" + entry + "</li>";
});
html += "</ul>";
return html;
});
and in your handlebars template;
{{printItems items}}
Above code will put your items in list.
For more details refer here. Go to helpers section
回答2:
Handlebars is a minimal tempting language for JavaScript and as such it will not let you execute arbitrary code from within a template. Handlebars does however provide you with helpers let you execute pre-defined code over your template. The built in ones are: each, unless, if and else.
You can create your own helpers with the Handlebars.registerHelper method. Here is a simple example that formats a phone number. So long as you register the helper before you call it you should be able to use {{formatPhoneNumber phoneNumber}} anywhere in your code.
Handlebars.registerHelper("formatPhoneNumber", function(phoneNumber) {
phoneNumber = phoneNumber.toString();
return "(" + phoneNumber.substr(0,3) + ") " +
phoneNumber.substr(3,3) + "-" +
phoneNumber.substr(6,4);
});
Note: While it may be technically possible to execute non-rendering code from within a helper, this is considered bad practice and should be avoided if at all possible.
回答3:
To deal with manupulations of data in handlebars template you need to add the helper and call that helper in the template.
Read more here...
http://blog.teamtreehouse.com/handlebars-js-part-2-partials-and-helpers
来源:https://stackoverflow.com/questions/21845710/calling-javascript-function-from-handlebar