使用路由器字符串加载 backbone 模板

Loading backbone template by using the router string

我正在创建 backbone 视图,它的内容是由路由器的参数字符串动态加载的。所以我创建了一个包含主模板和多个子模板的视图。

这是我的观点:

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] return 字符串,我无法将其存档。

如有任何建议,我们将不胜感激。

如果您只有几个动态可选择的模板,可以这样做:

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;
});