12
votes

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:

3

3 Answers

18
votes

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

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...
});
-3
votes

You can set the model property of the view 'model: {isMine:true}'