Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does nested each in template output nothing

While this is rendered as expected:

{{#each Items}}  // a collection
  {{title}}  
{{/each}}  
{{#each types}}  // another ollection
  {{refId}}  
{{/each}}  

if I put it together:

{{#each Items}}  
  {{title}}  
  {{#each types}}  
    {{refId}}  
  {{/each}} 
{{/each}} 

The #each types is empty.

The template helpers:

Template.menuItems.helpers({
    restMenuItems: function() {
        return RestMenuItems.find({restRefId: this._id}, {sort:Template.instance().sort.get()});
    },
    restMenuSideItems: function() {
        return RestMenuSideItems.find({restRefId: this._id},            {sort:Template.instance().sort.get()});
    }
});

Template.menuItems.onCreated( function(){
    this.subscribe('restMenuItems');
    this.subscribe('restMenuSideItems');
});

And some of the template code:

{{#each restMenuItems}}
  <div>
    <select class="list-group select_side_addons">
      {{#each restMenuSideItems}}
        <option>{{restRefId}}</option>
      {{/each}}
    </select>
  </div>
{{/each}}

Even when replacing {{#each restMenuSideItems}} by {{#each ../restMenuSideItems}}, nothing appears.

What's wrong?

like image 524
Avi A Avatar asked Oct 19 '22 16:10

Avi A


1 Answers

Because the #each clause changes the data context to the current item.

If you want a list of types inside each of the Items, you can get the parent data context using ...

If types is an attribute of the parent context:

{{#each Items}}  
  {{title}}  
  {{#each ../types}}  
    {{refId}}  
  {{/each}} 
{{/each}} 

If types is a template helper, you can pass the parent context as an argument to it:

{{#each Items}}  
  {{title}}  
  {{#each types ..}}  
    {{refId}}  
  {{/each}} 
{{/each}} 

and use the context for your query.

Template.myTemplate.helpers({

  types: function(parent) {
    // you now have the parent context here.
    // use parent._id etc. where you used this._id in the
    // "flat" version.
  }
});
like image 132
MasterAM Avatar answered Nov 15 '22 02:11

MasterAM