Calling Javascript function from handlebar

安稳与你 提交于 2019-12-04 22:23:51
Hüseyin BABAL

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

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.

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

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