Search code examples
javascriptmeteorspacebars

Why does #each tag not accept an array?


My optionData.js is as follows:

"options"=
[
{
  "option_text": "Just Me",
  "option_image": "just-me.svg",
  "option_is_selected": false
},
{
  "option_text": "Spouse/Partner",
  "option_image": "spouse-partner.svg",
  "option_is_selected": false
},
{
  "option_text": "Child/Children",
  "option_image": "child-children.svg",
  "option_is_selected": false
},
{
  "option_text": "Grand Children",
  "option_image": "grandchildren.svg",
  "option_is_selected": false
},
{
  "option_text": "Parent(s)",
  "option_image": "parents.svg",
  "option_is_selected": false
},
{
  "option_text": "Pet(s)",
  "option_image": "pets.svg",
  "option_is_selected": false
},
{
  "option_text": "Anyone Else",
  "option_image": "anyone-else.svg",
  "option_is_selected": false
}
]

This is my options.js file

calc_option_set1: function(){
    var options_set = this.options;
    option_count = options_set.length;
    upperRowObjects = [];

    if(option_count == 2)
    {
        rowBreak = -1;
    }
    else if(option_count % 2 == 0)
    {
        rowBreak = (option_count / 2);
    }
    else
    {
        rowBreak = (option_count + 1) / 2;
    }

    for(i=0; i<rowBreak; i++)
        upperRowObjects = upperRowObjects + options_set[i];
    return upperRowObjects;
},

This is options.html

{{#each option_set1}}
<div class="col-xs-2">
    <center>
        <img src="/images/{{option_image}}" class="img-responsive img-rounded img-option"/>
        <h5>{{option_text}}</h5>
    </center>
</div>
{{/each}}

Basically I want to divide the options and render them in two different rows(CSS). If I print {{calc_option_set1}} I get the set of objects I want. However, if I try to iterate over them as in the code, I get the error as

"Uncaught Error: {{#each}} currently only accepts arrays, cursors or falsey values."

How do I iterate over the array returned by the method ? Any way I can assign it to a variable and then use it? Please help...


Solution

  • Array concatenation does not work with the + operator. Use Array.push() instead.

    calc_option_set1: function(){
        var options_set = this.options;
        option_count = options_set.length;
        upperRowObjects = [];
    
        if(option_count == 2)
        {
            rowBreak = -1;
        }
        else if(option_count % 2 == 0)
        {
            rowBreak = (option_count / 2);
        }
        else
        {
            rowBreak = (option_count + 1) / 2;
        }
    
        for(i=0; i<rowBreak; i++)
            upperRowObjects.push(options_set[i]);
        return upperRowObjects;
    },
    

    and access it with:

    {{#each calc_option_set1}}
    {{/each}}