Search code examples
templatesmeteorspacebars

How to pass an array/objects with spacebars to a meteor template?


I am trying to construct a meteor template for simplifying creating radio buttons on a form. I would like to be able to pass an array or object as an argument through spacebars to the template. How can I pass an array/object as an argument or is this even possible?

Template:

<template name="radioButton">
  <div class="mdl-textfield mdl-js-textfield">{{radioLabel}}</div>
  {{#each getRadioOptions}}
  <label class="mdl-radio mdl-js-radio mdl-js-ripple-effect" for="{{radioOptionID}}">
    <input type="radio" id="{{radioOptionID}}" class="mdl-radio__button" name="{{radioID}}" value="{{optionID}}">
    <span class="mdl-radio__label">{{optionLabel}}</span>
  </label>
  {{/each}}
</template>

Template helper:

Template.radioButton.helpers({
    getRadioOptions: function () {
        console.log("getRadioOptions called");
        console.log(this);
        console.log(this.radioOptions);
        return this.radioOptions;
    },
    radioOptionID: function() {
        return this.radioID+"-"+this.optionID;
    }
});

Attempted spacebar notation:

{{> radioButton radioID="sampleID" radioLabel="Sample Radio Buttons"
    radioOptions=[{optionID:"option1",optionLabel:"Option One"},
                  {optionID:"option2",optionLabel:"Option Two"}] }}

After running this notation and looking at the browser console, I get back this: (which shows that only null was passed for radioOptions)

getRadioOptions called
Object {radioID: "sampleID", radioLabel: "Sample Radio Buttons", radioOptions: null}
null

Solution

  • You almost got it right, except that you can't give the data as a javascript array but need to use a JSON string, i.e., use:

    {{> radioButton radioID="sampleID" radioLabel="Sample Radio Buttons"
        radioOptions='[{"optionID":"option1", "optionLabel":"Option One"}, {"optionID":"option2","optionLabel":"Option Two"}]' }}
    

    Note that you need to use quotation marks around the field names, too, because it's JSON and not javascript!

    Then, in the helper, parse the string:

        getRadioOptions: function () {
            console.log("getRadioOptions called");
            console.log(this.radioOptions);  // string
            return JSON.parse(this.radioOptions);  // array
        },