Iron Router: How do I send data to the layout?

。_饼干妹妹 提交于 2019-12-24 04:26:10

问题


Using Iron Router, I understand how to set data for a template. But how do I send data to a layout that was globally defined?

I set the router layout by:

Router.configure({ layoutTemplate: 'NAME' })

This will set the layout for all my routes.

However from my individual routes, I'd like to send data to the layout template.


回答1:


The layout uses the data context defined with data in the route option. Here is an excerpt from Iron Router documentation:

Router.route('/routeName', {
  ...

  // A data function that can be used to automatically set the data context for
  // our layout. This function can also be used by hooks and plugins. For
  // example, the "dataNotFound" plugin calls this function to see if it
  // returns a null value, and if so, renders the not found template.
  data: function () {
    return Posts.findOne({_id: this.params._id});
  },

  ...
}

We can also set the data context of the layout with this.layout like this:

Router.route('/routeName', function () {
  this.layout('layoutName', {
    data: function() {
      return CollectionName.find();
    }
  });
});

In addition, we can refer to an existing layoutTemplate option like this:

Router.route('/routeName', function () {
  this.layout(this.lookupOption('layoutTemplate'), {
    data: function() {
      return CollectionName.find();
    }
  });
});



回答2:


Router.configure({
    layoutTemplate: 'NAME',
    data: function() {
        return CollectionName.find();
    }
});

As described in the Global Default Options in the iron:router docs:

You can set any of the above options on the Router itself...

Where 'above options' is referring to any of the Route Specific Options

You can also subscribe to a published Collection:

Router.configure({
    layoutTemplate: 'NAME',
    subscriptions: function() {
        this.subscribe('CollectionName');
    }
});


来源:https://stackoverflow.com/questions/28406970/iron-router-how-do-i-send-data-to-the-layout

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