Template two models in one view - Backbone/Marione

2019-03-19 20:25发布

问题:

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?

回答1:

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>


回答2:

try creating a complex model that contains the two models, this new model will have the other two as properties and you can acccess the properties of each one like this answer explains..

Access Nested Backbone Model Attributes from Mustache Template