简体   繁体   English

从车把调用Javascript功能

[英]Calling Javascript function from handlebar

How can I call a JavaScript function from inside a handlebars script? 如何从Handlebars脚本中调用JavaScript函数? Reason: 原因:

I wasn't able to break the {{#each}} from inside handlebars. 我无法从车把内部打破{{#each}} So I need to pass it to JavaScript to do the logic. 所以我需要将它传递给JavaScript来做逻辑。

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是JavaScript的最小诱人语言,因此它不允许您从模板中执行任意代码。 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 . 内置的是: eachunlessifelse

You can create your own helpers with the Handlebars.registerHelper method. 您可以使用Handlebars.registerHelper方法创建自己的帮助程序。 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. 只要您在调用之前注册帮助程序,您就可以在代码中的任何位置使用{{formatPhoneNumber phoneNumber}}

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. 要处理Handlebars模板中的数据操作,您需要添加帮助程序并在模板中调用该帮助程序。

Read more here... 在这里阅读更多......

http://blog.teamtreehouse.com/handlebars-js-part-2-partials-and-helpers http://blog.teamtreehouse.com/handlebars-js-part-2-partials-and-helpers

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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