Search code examples
meteoriron-routermeteor-blazespacebars

Multiple yield in Meteor.js application template


I have one general {{>yield}} for iron-router in a layout file which renders my pages, which are templates.

In one of my pages, I have a side menu and according to the selection in this menu, I want to load different templates related to this page in this page.

How can I achieve this?


Solution

  • I have done a similar thing using iron-router's layout template option. Say I want to create a home view with multiple views/templates inside of this home view that will change. First I would declare my route:

    Router.map(function () {
      this.route('home', {
      path: '/',
      template: 'myHomeTemplate',
      layoutTemplate: 'layout',
      yieldTemplates: {
        'myAsideTemplate': {to: 'aside'},
        'myFooter': {to: 'footer'}
        }
      });
    });
    

    Where the html for the layout template would look like:

     <template name="layout">
       <aside>
         {{> yield region='aside'}}
       </aside>
    
      <div>
        {{> yield}}
      </div>
    
      <footer>
        {{> yield region='footer'}}
      </footer>
    </template>
    

    So that the templates specified in the yields aside and footer get rendered in the specified spot. For your case you can specify a sidemenu yield.

    No that you have the basic layout and idea you can define another route. Say we call it differentHome.

    Router.map(function () {
      this.route('differentHome', {
      path: '/differentHome',
      template: 'myHomeTemplate',
      layoutTemplate: 'layout',
      yieldTemplates: {
        'myDifferentAsideTemplate': {to: 'aside'},
        'myDifferentFooter': {to: 'footer'}
        }
      });
    });
    

    Notice on this route declaration I am changing the yield templates, but I am not changing the basic template that will be rendered in the main yield. Now on an event you can re-route which will change the two different yields templates:

    Router.go("differentHome"); 
    

    Or you can use html to route, say with a link.

    EDIT (Haphazard Solution):

    Use Session Variable To Dictate Side Menu choice.

    HTML:
    <template name="main">
      ......
       <div class="sideMenu">   
         {{#if sideMenu1}}
            {{> side1Template}}
         {{/if}}
    
         {{#if sideMenu2}}
            {{> side2Template}}
         {{/if}}
       </div>
     </template>
    
    JS:
    Template.main.helpers({
        sideMenu1 : function () {
             return Session.equals("sideMenuChoice", "sideMenu1")  
        },
        sideMenu2 : function () {
             return Session.equals("sideMenuChoice", "sideMenu2")  
        }
     });
    

    Now on an event set the Session to what ever sideMenuChoice.