据我所知,marionette.template
接受jquery 选择器
或编译模板字符串
。
如果我按照以下方式编写代码,则工作正常
exports.ProductInfoView=Backbone.Marionette.ItemView.extend({
domInfo:{
mainTemplateId:"tagProductListTpl",
tableTemplateId:"taginfoViewTpl"
},
template:commomFunctions.templateCompilation("tagProductListTpl",""),
onRender:function(){
this.templatingProductInformation();
},
modelEvents:{
"change:currentJson":"templatingProductInformation"
},
templatingProductInformation:function(){
console.log(this.el);
//this.el.innerHTML=commomFunctions.templateCompilation(this.ui.mainTemplateId,"");
}
});
注意:commonFunctions.templateCompilation()
接受 templateId
作为第一个参数,data
作为第二个参数。它将编译handlebars template
并返回编译后的模板。
如果我将该返回值分配给template
,则工作正常。
我想为模板制作数据,因此我将 function
传递给 template,如下所示。
exports.ProductInfoView=Backbone.Marionette.ItemView.extend({
domInfo:{
mainTemplateId:"tagProductListTpl",
tableTemplateId:"taginfoViewTpl"
},
template:function(){
return commomFunctions.templateCompilation("tagProductListTpl","");
},
onRender:function(){
this.templatingProductInformation();
},
modelEvents:{
"change:currentJson":"templatingProductInformation"
},
templatingProductInformation:function(){
console.log(this.el);
//this.el.innerHTML=commomFunctions.templateCompilation(this.ui.mainTemplateId,"");
}
});
这种方式也工作得很好,如果你观察到我在函数内部硬编码了 templateId("tagProductListTpl")
。但我不想那样。我想使用像 this.domInfo.mainTemplateId
而不是硬编码。这样就无法正常工作。
抛出错误。我知道这超出了范围。但我怎样才能实现这个目标。
谁能帮帮我。
谢谢。
最佳答案
我建议你重写负责模板编译的Marionette.TemplateCache.prototype.compileTemplate
。看this帖子,几乎有同样的问题。
Marionette.TemplateCache.prototype.compileTemplate = function (yourRawTemplate) {
// In case if template is function
if (_.isFunction(yourRawTemplate)) {
return yourRawTemplate;
} else {
return Handlebars.compile(yourRawTemplate);
}
};
如果您从远程服务器加载模板文件,您还需要重写Backbone.Marionette.TemplateCache.prototype.loadTemplate
。这里的例子:
Marionette.TemplateCache.prototype.loadTemplate = function ( templateId ) {
var template = '',
templateUrl = 'path_to_your_template/' + templateId + '.html';
// Loading template synchronously.
Backbone.$.ajax( {
async : false,
url : templateUrl,
success : function ( templateHtml ) {
template = templateHtml;
}
} );
return template;
};
关于javascript - 如何将功能分配给 marionette.template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26438900/