提问者:小点点

如何将参数传递到主干木偶复合视图模板


有没有办法将参数输入到木偶复合视图模板中?我认为初始化视图时使用的任何参数都可以在模板中使用,但它似乎不起作用。

Views.myView = Marionette.CompositeView.extend({
  template: '#myView',
  otherstuff...
});


var collection = new App.Collection(); 
App.main.show(new Views.myView({
  collection: collection,
  isMine: true
}));

模板:

<%= isMine %> 

当模板呈现时isMy是未定义的:


共3个答案

匿名用户

您可以为此使用templateHelpers函数。例如,我有一个在渲染时填充不同区域的布局。

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

匿名用户

在freenode聊天室得到了brian mann的帮助来解决这个问题。我将该值传递给视图,但我需要通过重写serializeData方法将其作为属性发送给实际模板。

我还做了一个检查,将默认值设置为true,这样如果我不想,就不必传入值。

Views.myView = Marionette.CompositeView.extend({
  template: '#myView',
  serializeData: function() {
      var viewData = {};
      viewData.isMine = this.options.isMine === undefined ? true : this.options.isMine;
      return viewData;
    },
  otherstuff...
});

匿名用户

您可以设置视图的模型属性“模型:{isMy: true}”