質問

I have a backbone model set up where it uses a single itemview and template to display to the end user.

However, I have added a new attribute into the model, and based on the value of this new attribute I would like to use the correct template/itemview.

My backbone code is below:

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

So, somewhere (in the compositeview?) I need to say something alone the lines of:

if (this.model.get("infotype") === "blog") {
  // use different template (#template-blogwell)
}

Is this possible? Can I define two templates in my itemview and choose the correct on there, or do I need two itemviews and I say in my compositeview which one to use?

Thank you!

役に立ちましたか?

解決

This is covered in the Marionette JS Docs here:

There may be some cases where you need to change the template that is used for a view, based on some simple logic such as the value of a specific attribute in the view's model. To do this, you can provide a getTemplate function on your views and use this to return the template that you need.

Reusing your code,

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

他のヒント

Declare two templates and use them when required

like

 InfoWellView = Backbone.Marionette.ItemView.extend({
    template1 : "#template-infowell",
    template2 : "someOtherTemplate",
    tagName : 'div',
    className : 'alert alert-custom',
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top