Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template two models in one view - Backbone/Marionette

I'm trying to use two models in one view, and template using both of them. I'm working with Marionette. Here is me initialization of the view:

main_app_layout.header.show(new APP.Views.HeaderView({
 model: oneModel,
 model2 : twoModel}
));

Here is my view:

APP.Views.HeaderView = Backbone.Marionette.ItemView.extend({

    template : '#view_template',

    className: 'container',


    initialize: function() {
               //This correctly logs the second model
                console.log(this.options.model2);

    }

});

And here is the template:

 <script id="view_template" type="text/template">
        <p>{{twoModel_label}} {{oneModel_data}}</p>
        <p>{{twoModel_label2}} {{oneModel_data2}}</p>
    </script>

It renders everything correctly using the oneModel data, but doesn't render the second, even though it logs it correctly. I'm using Mustache as my templating language.

Can anyone help?

like image 322
streetlight Avatar asked Mar 28 '13 13:03

streetlight


1 Answers

You can override the serializeData method on your view and have it return both models' data:


APP.Views.HeaderView = Backbone.Marionette.ItemView.extend({

  // ...

  serializeData: function(){
    return {
      model1: this.model.toJSON(),
      model2: this.options.model2.toJSON()
    };
  }

});

Then your template would look like this:

<script id="view_template" type="text/template">
    <p>{{model1.label}} {{model1.data}}</p>
    <p>{{model2.label}} {{model2.data}}</p>
</script>
like image 171
Derick Bailey Avatar answered Sep 23 '22 18:09

Derick Bailey