Search code examples
meteoriron-router

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


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.


Solution

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