Search code examples
meteoreachhelper

return object value from helper (meteor)


I have a helper function which takes in a parameter and returns an object.

objectReturnHelper: function(param1) {
   var obj1 = collectionName.findOne(param1).count1;
   var obj2 = collectionName.findOne(param1).count2;;
   return {
        obj1: _.range(0, obj1),
        obj2: _.range(0, obj2)
    };
}

Now I want to access the values of the objects individually. This is how I am trying to do :

{{#each objectReturnHelper id obj1}}
        <p>TEST</p>
{{/each}}

But it is producing no results. But if I remove the parameter, it works fine :

objectReturnHelper: function() {
   var obj1 = 5;
   var obj2 = 10;
   return {
        obj1: _.range(0, obj1),
        obj2: _.range(0, obj2)
    };
}


{{#each objectReturnHelper.obj1}}
        <p>TEST</p>
{{/each}}

Any insights?


Solution

  • To better reflect the structure of your objects, you can use #with to properly access object context. Within this context you can create a range for each item, within the given range using #each

    {{#with objectReturnHelper id}}
      {{#each this.obj1}}
        <p>Test (1)</p>
      {{/each}}
      {{#each this.obj2}}
        <p>Test (2)</p>
      {{/each}}
    {{/with}}
    

    If your helper produces unexpected results you are going good with having a non invasive fallback:

    objectReturnHelper: function(param1) {
       var query = collectionName.findOne(param1)
       if (!query) return null
    
       var obj1 = query.count1;
       var obj2 = query.count2;
    
       return {
            obj1: obj1 >= 0 ? _.range(0, obj1) : null,
            obj2: obj1 >= 0 ? _.range(0, obj2) : null,
        };
    }
    

    You can then catch this fallback inside with using else that automatically triggers when the context is falsey:

    {{#with objectReturnHelper id}}
      {{#each this.obj1}}
        <p>Test (1)</p>
      {{/each}}
      {{#each this.obj2}}
        <p>Test (2)</p>
      {{/each}}
    {{else}}
      <p>No data found</p>
    {{/with}}
    

    You can of course configure it to a different fallback, where the else catches inside the each blocks:

    {{#with objectReturnHelper id}}
      {{#each this.obj1}}
        <p>Test (1)</p>
      {{else}}
        <p>No data found</p>
      {{/each}}
      {{#each this.obj2}}
        <p>Test (2)</p>
      {{else}}
        <p>No data found</p>
      {{/each}}
    {{/with}}