elanh
elanh

Reputation: 1451

Marionette.js: Rendering a different view for one model in a collection

I have a collection of models. I want to render the same view for all the models in that collection, except for one for which the view should be unique.

Normally, I would use a CollectionView to render the same ItemView for the whole collection, but that won't work in my case.

The options I've thought of are:

  1. Use the same ItemView for all models, but have some logic in it that renders something different for that specific model.
  2. Use a CompositeView which gets the collection without the unique model, and gets that unique model as its model. Then render the collection one way, and the model some other way.

Which option is better? Are there any other suggestions?

Upvotes: 0

Views: 420

Answers (2)

bryanbuchs
bryanbuchs

Reputation: 471

I have a similar-ish use case with a nested set of collections. I'm using CompositeView to recursively render all the nodes of the tree, each of which might need a slightly different template. By using the getTemplate method I can inspect the model and use one of several different templates. Pretty much what @David outlined, but here's an example:

getTemplate: function(){
  var template;
  switch (this.model.get('type')) {
    case 'film':
      template = 'film';
      break;
    case 'item':
      template = 'item';
      break;
    case 'year':
    case 'decade':
      template = 'node';
      break;
  }
  return template;
},

Upvotes: 2

David Sulc
David Sulc

Reputation: 25994

I would go with your second idea: use a composite view that receives the "special model" and a collection.

But if you have one model that needs to be treated differently, you might want to reconsider your data structure. It seems like an unusual setup, but maybe there's a better way to approach the problem.

Upvotes: 0

Related Questions