如果在Handlebars.js中预编译自定义帮助程序,如何注册自定义帮助程序

How do you register a custom helper if you are precompiling a custom helper in Handlebars.js?

本文关键字:帮助程序 自定义 何注册 注册 js 编译 如果 Handlebars      更新时间:2023-09-26

我正试图用命令handlebar app/views/templates/walrus.handlebar预编译Handlebars.js模板app/views/templates/walrus.handlebar,但它失败了,因为该模板使用了我在单独的js文件public/javascripts/handlebar_helpers.js中定义的自定义帮助程序。

我该如何调用Handlebars的命令行版本,以便它知道带有自定义助手的javascript文件?

handlebars <input> -f <output> -k <helper>

它在这里的文档中:http://handlebarsjs.com/precompilation.html

编辑2014年3月:

对于在阅读文档时遇到问题的人,这里有一个自定义助手"全名"的例子

handlebars myTemplate.handlebars -f handlebars-fullname.js -k fullname

有了这个助手:

Handlebars.registerHelper('fullname', function(person) {
  return person.firstName + " " + person.lastName;
});

您仍然需要在带有handlebars.runtime.js 的页面中包含帮助程序

handlebars myTemplate.handlebars -f handlebars-fullname.js -k fullname

上面的步骤不是强制性的,即使在预编译期间没有指定帮助程序名称,您的手把模板也可以工作,但是需要在客户端上插入以下代码(基本上应该包含所有帮助程序)

    Handlebars.registerHelper('fullname', function(person) {
  return person.firstName + " " + person.lastName;
});

我试过这个,效果很好!