Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Radio inputs with Mustache templates

Tags:

mustache

I'm trying to use mustache templates to render very simple forms, however, one of the forms has a collection of radio buttons. I can't figure out how to have the right radio button selected when the form is rendered.

Is this something that is simple and I'm just missing something, or does the "logic-less" aspect of mustache really prevent me rending something as basic as a radio button?

My data looks something like this:

data = { gender: 'female' }

<form>
  <label><input type="radio" name="gender" value="male"> Male</label>
  <label><input type="radio" name="gender" value="female"> Female</label>
</form>
like image 764
Jeremy Baker Avatar asked Mar 04 '12 18:03

Jeremy Baker


2 Answers

You can do this using a lambda:

var data = {
    gender: 'female',
    wrapped: function () {
        return function (text) {
            return text.replace('value="' + this.gender+'"', 'value="' + this.gender+'" checked');
        }
    }
};

<form>
    {{#wrapped}}
    <label><input type="radio" name="gender" value="male"> Male</label>
    <label><input type="radio" name="gender" value="female"> Female</label>
    {{/wrapped}}
</form>

Have a look at the full example I used if you have any trouble.

Update:

Justin Hileman showed me another way of doing this:

<form>
<label><input type="radio" name="gender" value="male"{{#maleIsDefault}} checked{{/maleIsDefault}}>
Male</label>
<label><input type="radio" name="gender" value="female"{{#femaleIsDefault}} checked{{/femaleIsDefault}}> Female</label>
</form>

var data = {
        gender: 'female',
        maleIsDefault: function() {
            return this.gender == 'male';
        },
        femaleIsDefault: function() {
            return this.gender == 'female';
        }
};

Full example here.

like image 132
ebaxt Avatar answered Sep 20 '22 17:09

ebaxt


Another option, with coffeescript (untested)...

// define radio button options in an array
genders = [
  { code: 'M', name: 'Male' }
  { code: "F", name: "Female" }
]

// flag the current object as "selected"
for g in genders
  if g.code == existingGenderValue
    g.selected = true

Then in mustache, dynamically generate your buttons based on the genders array:

{{#genders}}
  <label class="radio">
    <input type="radio" name="gender" value="{{code}}" {{#selected}} checked="checked" {{/selected}}>
    {{name}}
  </label>
{{/genders}}
like image 42
Sam Pierce Lolla Avatar answered Sep 19 '22 17:09

Sam Pierce Lolla