Search code examples
meteormeteor-blazemeteor-helper

How can I return options for an HTML select from a Template Helper in Meteor?


I thought I could return the options for an HTML select element something like this:

In the Template's .HTML file:

  <select id="stateorprovince" name="stateorprovince">
    {{statesAndProvinces}}
  </select>

In the Template's .js file (bogus data for now; will replace with US States and Canadian Provinces, at least):

Template.addJobLoc.helpers({
  statesAndProvinces: function() {
    return
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  }
});

...but it fails to build with a syntax error at the start of the first "option"

If I enclose the options in single quotes, the error is "Unexpected token ILLEGAL'

What is the correct way to accomplish this?


Solution

  • You could use this approach which is better suited than returning HTML from a template helper :

    HTML

    <template name="addJobLoc">
      <select id="stateorprovince" name="stateorprovince">
        {{#each statesAndProvinces}}
          <option value="{{value}}">{{label}}</option>
        {{/each}}
      </select>
    </template>
    

    JS

    Template.addJobLoc.helpers({
      statesAndProvinces: function(){
        return [{
          value: "volvo",
          label: "Volvo"
        },{
          value: "saab",
          label: "Saab"
        }, ...];
      }
    });
    

    Here we're returning an hardcoded array within the helper for the sake of simplicity but you could also return collection data.