如何在Handlebars中使用带有RequireJS的预编译模板?

Cha*_*son 7 requirejs client-side-templating handlebars.js

我想预编译我的Handlebars模板,但我不确定它在开发模式下是如何工作的.

通常的做法是有一些像Guard一样的后台进程来持续监控Handlebars模板文件的变化吗?

我正在使用RequireJS来提取模板; 例如:

define(['jquery', 'handlebars', 'text!templates/my_template'], function($, Handlebars, myTemplate) {

  // ...

  var data = {"some": "data", "some_more": "data"};
  var templateFn = Handlebars.compile(myTemplate);
  $('#target').append(templateFn(data));

  // ...

});
Run Code Online (Sandbox Code Playgroud)

所以我理解一旦模板被预编译,就可以这样做:

define(['jquery', 'handlebars'], function($, Handlebars) {

  // ...

  var data = {"some": "data", "some_more": "data"};
  var template = Handlebars.templates['my_template'];
  $('#target').append(template(data));

  // ...

});
Run Code Online (Sandbox Code Playgroud)

请注意以下有关第二个代码段中的内容:

  1. RequireJS模块不再拉入模板.
  2. 不再使用Handlebars.compile().

因此,只要文件系统级修改发生在模板文件中,我通常会运行Guard以保持模板编译?

基本上我的问题是,开发人员打算这样做吗?

if (development) {
  compile templates
}
else {
  use precompiled templates
}
Run Code Online (Sandbox Code Playgroud)

我也在使用Rails,所以也许有一些黑魔法像sass-rails.

Ian*_*Lim 11

您是否看过Require.js Handlebars插件(https://github.com/SlexAxton/require-handlebars-plugin)或epeli的requirejs-hbs(https://github.com/epeli/requirejs-hbs)?