How to pass parameter to backbone marionette composite view template
Asked Answered
P

3

12

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:

Perdu answered 18/1, 2013 at 18:48 Comment(0)
A
18

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
            }
        }
    });
Anabiosis answered 11/11, 2013 at 15:58 Comment(2)
+1 This is the correct method. You can also pass a straight object to templateHelpers, rather than a function, if anyone was wondering :)Bighead
Although if you do pass in an object, you won't have direct access to the "this" keyword. (Sorry, it wouldn't allow me to edit my comment!)Bighead
P
6

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...
});
Perdu answered 18/1, 2013 at 20:51 Comment(0)
G
-3

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

Goldenrod answered 19/1, 2013 at 12:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.