meteormeteor-blazemeteoritemeteor-helper

Meteor loops and conditional data


Given a years worth of months and data that returned may only apply to specific months, how can I render this in blaze please, but also render 0's where an applicable record does not exist?

What I'm working with:

{{#each month in months}}
  {{#each recordDataset }}
    {#if equals recordDataset.period month}<td>{{ recordDataset.value}}</td>{/if}
  {{/each}}
{{/each}}

This nested loop obviously returns too many because it is looping through 2 separate sets of data. I can think how to do this in other languages of course but not in blaze.

For example, what would be ideal would be:

{{#each month in months}}
  {{#if recordSet['month'] == month}}
    <td>{{ recordDataset.value}}</td>
  {{else}}
    <td>&nbsp;</td>
  {{/if}}
{{/each}}

But I don't see how I can achieve this.

Any help would be hugely appreciated.


Solution

  • Based on your code example, recordDataSet has a property month which you'd like to compare to each month in months. Given that, you can just create an equals operator and use that for comparison:

    Template.registerHelper( 'equals', ( v1, v2 ) => {
      return v1 === v2;
    });
    
    {{#each month in months}}
      {{#if equals recordDataSet.month month}}
        <td>{{recordDataset.month}}</td>
      {{else}}
        <td>0</td>
      {{/if}}
    {{/each}}
    

    Since I don't have the schema of your recordDataSet, you'll have to adjust according to your needs.