Template two models in one view - Backbone/Marionette

£可爱£侵袭症+ 提交于 2019-12-04 10:55:49

问题


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



来源:https://stackoverflow.com/questions/15683743/template-two-models-in-one-view-backbone-marionette

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!