BobFranz
BobFranz

Reputation: 250

How to get access to outside properties in a nested {{#each}}?

I have an {{#each}} block that runs through a list of stops that a driver must make. Each stop needs to have a select run and the select draws in from another collection. So I have the select in another {{#each}}.

Now I need to programmatically check if a driver was already selected in the db for this particular stop as the select is running and have it get selected.

My problem is that I need to access info from the external {{#each}} to do the comparison in the internal {{#each}}.

Below is the code that I have but when I run it the stopNum is undefined.

Any help here is greatly appreciated.

<td class="text-left">
    {{#if notEquals stopNum 0}}
    <select class="form-control driverName clearForm" id="driverName{{stopNum}}" name="driverName{{stopNum}}">
        <option value="" ></option>
        {{#each drivers}}
        {{#if dispatchDriverSelected driversName stopNum}}
        <option value="{{driversName}}" selected>{{driversName}}</option>
        {{else}}
        <option value="{{driversName}}">{{driversName}}</option>
        {{/if}}
        {{/each}}
    </select>
    {{/if}}
</td>

Upvotes: 0

Views: 47

Answers (1)

MasterAM
MasterAM

Reputation: 16478

Within #each, the context is set to the current element.

If you want to get an external item/property, you can get the parent context using .. in the template code or using Template.parentData(numLevels) in helpers:

{{#each drivers}}
    {{#if dispatchDriverSelected driversName ../stopNum}}
        <option value="{{driversName}}" selected>{{driversName}}</option>
    {{else}}
        <option value="{{driversName}}">{{driversName}}</option>
    {{/if}}
{{/each}}

Here is a simple example:

Template structure:

<template name="example">
  {{#with datum}}
    <div class="wrapper">
    {{outer}}
    <div class="items">
      {{#each inner}}
        <div class="inner">
        {{prop}} {{someFunc ../outer}}
        </div>
      {{/each}}
    </div>
  </div>
  {{/with}}
</template>

Helpers:

Template.example.helpers({
  datum() {
    return {
      outer: 'outer 1',
      inner: [{
        prop: 'inner 1'
      },{
        prop: 'inner 2'
      }]
    }
  },
  someFunc(datum) {
    return `processed ${datum}`;
  }
});

renders to:

<div class="wrapper">
  outer 1
  <div class="items">          
    <div class="inner">
      inner 1 processed outer 1
    </div>

    <div class="inner">
      inner 2 processed outer 1
    </div>

  </div>
</div>

Upvotes: 1

Related Questions