使用RequireJS预编译的Handlebars模板

Precompiled Handlebars template with RequireJS

本文关键字:Handlebars 模板 编译 RequireJS 使用      更新时间:2023-09-26

我有一个手把模板,我已经手动预编译并保存为-testTemplate.handlebars.

现在,在我的requireJS+主干代码中,我有以下函数-

define(['text!../templates/testTemplate.handlebars'
       ],function(testTemplate){
           var myView = Backbone.View.extend(
              initialize: function(options){
                  this.template = Handlebars.template(testTemplate);
              },
              render: function(data){
                  $(this.el).html(this.template(data));
              }
           );
});

因此,testTemplate.handlebars以字符串的形式返回Javascript代码,当传递给handlebars.template时,返回JS函数。当我试图在控制台上打印我在this.template变量中得到的值时,它显示-

function (n,r){return r=r||{},e.call(t,Handlebars,n,r.helpers,r.partials,r.data)}

但是,当render函数的$(this.el).html(this.template(data));行执行时,它会给出一条错误消息,称UncaughtTypeerror:object没有方法调用。(尽管我可以看到e.call函数)

我是不是做错了什么?

此外,当我尝试编译模板运行时,render函数也能工作。当运行时编译Handlebars.compile(testTemplate)时,返回以下函数-

function (e,t){return n||(n=r()),n.call(this,e,t)}

如果您已经预编译了它,我不确定您是否需要调用.template。给定的函数应该作为模板本身是可执行的。所以这个:

$(this.el).html(this.template(data));

变为:

$(this.el).html(testTemplate(data));