Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameter to backbone marionette composite view template

Is there a way to get a parameter in to a marionette composite view template? I figured that whatever parameters I initialized the view with would be available in the template, but it doesn't seem to work.

Views.myView = Marionette.CompositeView.extend({
  template: '#myView',
  otherstuff...
});


var collection = new App.Collection(); 
App.main.show(new Views.myView({
  collection: collection,
  isMine: true
}));

template:

<%= isMine %> 

And when the template is rendered isMine is undefined:

like image 311
flynfish Avatar asked Jan 18 '13 18:01

flynfish


2 Answers

You can use the templateHelpers function for this. For instance I have a Layout that on render fills different regions.

onRender: function () {
            var contactInfo = this.model.get('contactInfo');

            this.contactInfoRegion.show(new ContactInfoView(
                {
                    model: contactInfo,
                    travelerNumber: this.travelerNumber,
                    numberOfTravelers: this.numberOfTravelers
                }
            ));
}

var ContactInfoView = Backbone.Marionette.ItemView.extend({
        model: ContactInfoModel,
        template: Backbone.Marionette.TemplateCache.get(contactInfoTemplate),
        templateHelpers:function(){

            return {
                numberOfTravelers: this.options.numberOfTravelers,
                travelerNumber: this.options.travelerNumber
            }
        }
    });
like image 73
The Pax Bisonica Avatar answered Oct 17 '22 08:10

The Pax Bisonica


Got some help from brian-mann in the freenode chatroom to figure this out. I passed the value to the view, but I need to send that as a property to the actual template by overriding the serializeData method.

I also do a check to set the default as true so I don't have to pass in the value if I don't want to.

Views.myView = Marionette.CompositeView.extend({
  template: '#myView',
  serializeData: function() {
      var viewData = {};
      viewData.isMine = this.options.isMine === undefined ? true : this.options.isMine;
      return viewData;
    },
  otherstuff...
});
like image 30
flynfish Avatar answered Oct 17 '22 08:10

flynfish