Javascript 使用路由器字符串加载主干模板
我正在创建主干视图,它的内容由路由器的参数字符串动态加载。因此,我创建了一个包含主模板和多个子模板的视图 以下是我的看法:Javascript 使用路由器字符串加载主干模板,javascript,templates,backbone.js,underscore.js,Javascript,Templates,Backbone.js,Underscore.js,我正在创建主干视图,它的内容由路由器的参数字符串动态加载。因此,我创建了一个包含主模板和多个子模板的视图 以下是我的看法: define(["jquery" , "underscore" , "backbone" , "text!templates/Content/confirmMessageTemplate.html", "text!templates/Content/registerMessage.html", "text!templates/Content/signInMessa
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]
返回字符串,我无法将其存档
任何建议都将不胜感激。如果您只有几个可动态选择的模板,可以这样做:
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;
});
像这样的东西render:function(){tmpPath=this.options.title[0].charAt(0).toUpperCase()+this.options.title[0].slice(1);require(tmpPath,function(path){var tmp=.\var.template(path);this.$el.html(…)})`
this.templatesHash[this.options.title[0]当我在浏览器中执行控制台时,
未定义。请检查一下,控制台中的this.templatesHash
打印了什么?还有,this.options.title[0]
。酷,那么this.templatesHash[this.options.title[0]
未定义的唯一原因就是this.options.title[0]
不在该对象的键中,可能是您必须根据您的需要更改该逻辑。啊…我知道了,我已将标题
更改为标题
,这就是它未定义的原因。现在,它已被修复。但我仍然有一个问题,尽管某些路由器字符串没有模板,那么我该怎么办。如果路由器stri如果没有模板,那么您希望subtem
变量包含什么值?