我正在创建骨干视图,其内容由路由器的参数字符串动态加载。所以我创建了一个包含主模板和多个子模板的视图。
以下是我的观点:
define(["jquery" ,
"underscore" ,
"backbone" ,
"text!templates/Content/confirmMessageTemplate.html",
"text!templates/Content/registerMessage.html",
"text!templates/Content/signInMessage.html"
],function($ , _ ,Backbone,ConfirmMessageTem,RegisterMessage,SignInMessage){
var teView = Backbone.View.extend({
initialize: function(options) {
this.options = options || {};
},
render: function(){
var message = _.template(ConfirmMessageTem);
var subtem = _.template(RegisterMessage);
this.$el.html(message({msgheader:this.options.msgheader, body:subtem()}));
}
});
return teView;
});
body:subtem()
将子模板投放到主模板。
this.options.title[0]
获取字符串值(RegisterMessage,SignInMessage,.....)所以我想要的是动态加载我的子模板,如:
var subtem = _.template(this.options.title[0]);
但由于this.options.title[0]
返回字符串,我无法将其归档。
任何建议都将不胜感激。
答案 0 :(得分:0)
如果您只有几个可动态选择的模板,可以这样做:
define(["jquery" ,
"underscore" ,
"backbone" ,
"text!templates/Content/confirmMessageTemplate.html",
"text!templates/Content/registerMessage.html",
"text!templates/Content/signInMessage.html"
],function($, _, Backbone, ConfirmMessageTem, RegisterMessage, SignInMessage){
var teView = Backbone.View.extend({
// make a hash of templates and attach that hash to teView, where key of
// the hash would be the router string that is returned in
// this.options.title[0] in your render method
templatesHash: {
"RegisterMessage": RegisterMessage,
"SignInMessage": SignInMessage
},
initialize: function(options) {
this.options = options || {};
},
render: function(){
var message = _.template(ConfirmMessageTem);
// and here subtem can be initialized as below -
// by reading the template from the templatesHash
// var subtem = _.template(RegisterMessage);
var subtem = _.template( this.templatesHash[ this.options.title[0] ] );
this.$el.html(message({msgheader:this.options.msgheader, body:subtem()}));
}
});
return teView;
});