Search code examples
javascriptmeteorspacebars

How Do I Properly Scope Nested #each Spacebars Iterators When Using Meteor?


I have these nested iterators:

<ul class='detailViewList'>
    {{#each detailsCollection}}
    <li id={{_id}} class='detailViewEntry {{checkboxStatus}}'>
        <input type="checkbox" class='detailCheckbox'>
        <b>{{detail}}</b>
        <div class="btn btn-xs btn-danger" id="delete-detail">x</div>
        <form class='form-inline'>
            <div class="form-group">
                <input type="text" id='{{_id}}' name='message' class="form-control" placeholder="message">
            </div>
        </form>
        {{#each messagesCollection}}
            {{#if isMessageForThisDetail}}
                {{message.message}}
            {{/if}}
        {{/each}}
    </li>
    {{/each}}
</ul>

And I understand that I can access parent attributes from child template via handlebars path, from docs:

{{./name}} or {{this/name}} or {{this.name}}

But I need my helper isMessageForThisDetail to compare an attribute of the currently iterated messageCollection to the currently iterated parent detailsCollection. My helper for that looks like this:

isMessageForThisDetail: function(){
    var message = messagesCollection.findOne({detailId: this._id});
    if(message != undefined){
        return this._id == message._id;
    } else {
        console.log('there is no message for this detail');
    }
}

But the context of this._id is the message, not the _id of the detail I want to compare a field of the message to.


Solution

  • You should be able to access the parent data like so:

    isMessageForThisDetail: function() {
        var detailId = Template.parentData(1)._id;
        var message = messagesCollection.findOne({detailId: detailId});
        if(message)
          return this._id === message._id;
        else
          console.log('there is no message for this detail');
    }