I'm trying to manipulate itemViews dynamically in a Marionette CollectionView. The collections have the same models, but i defined templateName argument inside the models.
The question is, can i manipulate the ItemView template by this argument?
ItemView:
define(['text!templates/ComponentItemViewTemplate.html','models/ComponentModel'], function (template, model) {
var ItemView = Backbone.Marionette.ItemView.extend({
template: _.template(template),
model: model
});
return ItemView;
});
CollectionView:
define(['views/ComponentItemView', 'views/LoadingView'], function(ItemView, LoadingView) {
var ComponentListView = Backbone.Marionette.CollectionView.extend({
emptyView : LoadingView,
id: "component-list",
itemView: ItemView,
events: {
'click .title span' : 'show'
},
appendHtml: function(collectionView, itemView, index){//i would like to render different templates, for different models.
itemView.$el.draggable({ helper: "clone", cancel: ".component .title span", connectToSortable: ".ui-sortable" });
collectionView.$el.append(itemView.el);
},
show: function(r) {
var target = $(r.target);
if( target.parent().hasClass('open') ){
target.parent().removeClass('open');
target.parent().next().slideDown('fast');
}else{
target.parent().addClass('open');
target.parent().next().slideUp('fast');
}
}
});
return ComponentListView;
});
Thanks!
You can override getTemplate function and write your custom logic there. The Marionette documentation recommends the following option:
MyView = Backbone.Marionette.ItemView.extend({
getTemplate: function(){
if (this.model.get("foo")){
return "#some-template";
} else {
return "#a-different-template";
}
}
});
I think gumballhead is on the right track. You can override the getTemplate
function to do this.
MyCollectionView = Marionette.CollectionView.extend({
// ...
getItemView: function(item){
// get the template from the item... or wherever else it comes from
return new MyViewType({
template: item.get("the-template")
});
}
});
Hope that does what you need
First of all i'd like to thanks for everybody who tried to help me. I resolved my own problem. Here is the sollution, if somebody need it:
define(['models/ComponentModel'], function (model) {
var ItemView = Backbone.Marionette.ItemView.extend({
model: model,
render: function() {
var that = this;
var data = this.serializeData();
require(['text!templates/components/editor/' + that.model.get('editor_template') + '.html'], function(Template){
var html = _.template(Template, data);
that.$el.html(html);
});
}
});
return ItemView;
});
edited: (Better sollution)
Suggestions are welcome!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With