Javascript 主干:基于模型值呈现不同的ItemView

Javascript 主干:基于模型值呈现不同的ItemView,javascript,backbone.js,model,marionette,Javascript,Backbone.js,Model,Marionette,我建立了一个主干模型,它使用单个itemview和模板向最终用户显示 但是,我已经在模型中添加了一个新属性,基于这个新属性的值,我希望使用正确的模板/项目视图 我的主干代码如下: InfoWell = Backbone.Model.extend({}); InfoWells = Backbone.Collection.extend({ model : InfoWell }); InfoWellView = Backbone.Marionette.ItemView.extend({

我建立了一个主干模型,它使用单个itemview和模板向最终用户显示

但是,我已经在模型中添加了一个新属性,基于这个新属性的值,我希望使用正确的模板/项目视图

我的主干代码如下:

InfoWell = Backbone.Model.extend({});

InfoWells = Backbone.Collection.extend({
    model : InfoWell
});

InfoWellView = Backbone.Marionette.ItemView.extend({
    template : "#template-infowell",
    tagName : 'div',
    className : 'alert alert-custom',

initialize: function () {
    this.$el.prop("id", this.model.get("datetime"));
},
});

InfoWellsView = Backbone.Marionette.CompositeView.extend({
    tagName : "div",
    id : "info-well-list",
    template : "#template-infowells",
    itemView : InfoWellView,

});

MainJs.addInitializer(function(options) {
    var aInfoWellsView = new InfoWellsView({
        collection : options.InfoWells
    });
    MainJs.InfoWellsContainer.show(aInfoWellsView);
});

var InfoWells = new InfoWells();
所以,在某个地方(在compositeview?)我需要单独说几句话:

if (this.model.get("infotype") === "blog") {
  // use different template (#template-blogwell)
}
这可能吗?我可以在itemview中定义两个模板并在那里选择正确的模板吗?或者我需要两个itemview并在compositeview中指定要使用哪一个模板


谢谢大家!

木偶JS文档中介绍了这一点:

在某些情况下,您可能需要更改 用于视图,基于一些简单的逻辑,例如 视图模型中的特定属性。为此,您可以提供 在视图上使用getTemplate函数并使用它返回模板 你需要的

重用代码

InfoWellsView = Backbone.Marionette.CompositeView.extend({
    tagName : "div",
    id : "info-well-list",
    template : "#template-infowells",
    itemView : InfoWellView,
    getTemplate: function () {
        if (this.model.get("infotype") === "blog") {
          // use different template (#template-blogwell)
        }
    }
});

声明两个
模板
并在需要时使用它们


谢谢没有意识到这是可能的(当然,很乐意帮忙。我的意思是,你应该先看一下木偶的官方文件——它非常详细。实际上,我从来没有在主干或木偶条上使用过SO。谢谢,我已经将另一个答案标记为答案,尽管它使用了内置的Backbone.marionete函数。感谢帮助=)我不确定这是否有效-
ItemView.prototype.render()
搜索使用
模板的
getTemplate()
失败<代码>模板1
模板2
将不会被拾取。
 InfoWellView = Backbone.Marionette.ItemView.extend({
    template1 : "#template-infowell",
    template2 : "someOtherTemplate",
    tagName : 'div',
    className : 'alert alert-custom',