我有一个 handlebars 模板,我手动预编译并保存为 - testTemplate.handlebars。
现在,在我的 requireJS + Backbone 代码中,我有以下功能 -
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)}
但是,当渲染函数的行 - $(this.el).html(this.template(data));
执行时,它给出一条错误消息说 - Uncaught Typeerror : object没有方法调用。 (尽管我可以看到一个 e.call 函数)
我是不是做错了什么?
此外,当我尝试编译模板运行时时,呈现函数可以正常工作。 在运行时编译 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));
关于javascript - 使用 RequireJS 预编译的 Handlebars 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18279390/