Calling Javascript function from handlebar

回眸只為那壹抹淺笑 提交于 2019-12-22 01:23:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!