Reputation: 1596
I'm in the process of setting up a website with a blog that has some peculiarities. It's sort of a tumblr-esque experience, where there's different post-type:
These posts share some common attributes such as id
, title
, post_date
, post_url_slug
, but some have a post_image
or post_external_link
for example. This is all dependent on the post_type
, which can hold values such as facebook
, quote
, article
etc. What would be a good strategy to determine which type it is when rendering a Marionette.CollectionView
and either selecting a different tempalte altogether or handling this in the template with underscore's arbitrary javascript in my template? Any input would be appreciated.
Thanks!
Upvotes: 2
Views: 688
Reputation: 471
You should have one single ItemView, don't need to override getItemView of the CollectionView. The ItemView should be the one in charge of deciding the template to use, that's what getTemplate is for. It should look like this:
var MyItemView = Marionette.ItemView.extend({
getTemplate: function() {
var template;
switch(this.model.get('type')) {
case 'facebook':
template = 'Template for Facebook type';
break;
case 'quote':
template = 'Template for Quote type';
break;
case 'article':
template = 'Template for Article type';
break;
}
return template;
}
});
This way you only have one ItemView for the one model you have and the rendering decisions are left to the template as it should be.
Upvotes: 1
Reputation: 72868
Definitely don't put the logic in the view template. That will lead to pain, suffering, hate and the dark side. :P
You can override the getItemView
method on the CollectionView or CompositeView and use that to determine which view type you want. https://github.com/marionettejs/backbone.marionette/blob/master/src/marionette.collectionview.js#L122
var Stuff = Marionette.CollectionView.extend({
// ...,
getItemView: function(item){
var type = item.get("whatever_field");
var viewType;
if (type === "some value"){
viewType = SomeViewType;
} else {
viewType = AnotherViewType;
}
return viewType;
}
});
Upvotes: 6
Reputation: 1
You could handle this in the ItemView intialize function and switch the template there. So long as you are planning to use the same events cross post type
Upvotes: 0