Passing values from an array to child template in meteor

198 views Asked by At

I've been grappling with the following problem:

I have two templates:

intervalsList
intervalIcon

I want intervalsList to populate with a list of intervalIcons.

Each intervalIcon displays a number; there is an array of these numbers:

[1, 5, 10, 15, 30, 45, 60] 

The intervalsList template iterates through this array, instantiating an intervalIcon for each index:

{{#each interval}}
    {{> intervalIcon}}  
{{/each}}

interval is defined as an array, as a helper of intervalsList:

Template.intervalsList.helpers({
    'interval': [1, 5, 10, 15, 30, 45, 60]
});

This works. A number of intervals are instantiated that corresponds with the size of the array.

However, I still need to display the number from each index of the array within an interval. (For instance, within a list item.)

e.g.

Array [1, 5, 10, 15, 30, 45, 60] outputs:

  • 1
  • 5
  • 10
  • 15
  • 30
  • 45
  • 60

I've tried the following:

<template name="intervalsList">
  {{#each interval}}
    {{> intervalIcon data={{this}} }}
  {{/each}}
</template>

Which at runtime is not accepted:

    While building the application:
client\views\settingsGeneral\settingsGeneral.html:18: Expected identifier, number, string, boolean, or null
...{> intervalIcon data={{this}}}}  
    {{/eac...
                        ^

I'm using two templates instead of one because the second template (intervalIcon) contains a Chart.js chart, which is complicated enough that I'd like to keep it separate from the first template.

How can I pass the value from the interval array retrieved during intervalList's #each loop to a sub-template, so that I can use it there?

I've looked at this question: Is there a way to pass variables into templates in Meteor? It mentions something about using ../ to reference a nested template's parent's data context, but I didn't really understand it.

Thank you so much!!

1

There are 1 answers

1
saimeunt On BEST ANSWER

There's no need to explicitly pass the currently iterated over item to the child template, it is automatically done by Spacebars.

Inside your intervalIcon template, you can refer to the item value using {{this}}.

<template name="intervalIcon">
  <p>{{this}}</p>
</template>

You can also give the interval value a name by replacing your array values by objects :

JS

Template.intervalsList.helpers({
  interval: function(){
    return [1, 5, 10, 15, 30, 45, 60].map(function(value){
      return {
        value: value
      };
    });
  }
});

HTML

<template name="intervalIcon">
  <p>{{value}}</p>
</template>