set the first radio button is checked in handlebar

2020-07-09 10:13发布

问题:

How can i get a easy and clear way that set the first radio button is checked in Handlebars template. tks

template:

<form>
    {{#each this}}
        <input value="{{value}}" />
     {{/each}}
</form>

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

expect render:

<form>
    <input value="val 1" checked />
    <input value="val 2" />
    <input value="val 3" />
</form>

thanks all.

回答1:

{{#each}} in Handlebars doesn't give you access to the iteration number or anything like that so you can't do it without altering your template and data a little bit:

<form>
    {{#each this}}
        <input type="radio" value="{{value}}" {{#if sel}}checked="checked"{{/if}} />
    {{/each}}
</form>

and then add sel values to your data:

var tmpl = Handlebars.compile($('#t').html());
var html = tmpl([
    { value: 'val 1', sel: true  },
    { value: 'val 2', sel: false },
    { value: 'val 3', sel: false }
]);

Demo: http://jsfiddle.net/ambiguous/27Ywu/

You could of course just set sel: true on the first element of your data array:

data = [ ... ];
data[0].sel = true;
var html = tmpl(data);

Demo: http://jsfiddle.net/ambiguous/yA5WL/

Alternatively, use jQuery to check the first one after you have the HTML:

// Add the HTML to the DOM...
$('form input:first').prop('checked', true); // Or whatever selector matches your HTML

Demo: http://jsfiddle.net/ambiguous/sPV9D/


Newer versions of Handlebars do give you access to the index:

When looping through items in each, you can optionally reference the current loop index via {{@index}}

{{#each array}}
  {{@index}}: {{this}}
{{/each}}

For object iteration, use {{@key}} instead:

{{#each object}}
  {{@key}}: {{this}}
{{/each}}

So, if you're using the latest Handlebars, you can do something special by using the fact that:

  1. The first @index will be zero.
  2. Zero is falsey in a boolean context.

That lets you do this:

{{#each this}}
    <input type="radio" value="{{value}}" {{#unless @index}}checked="checked"{{/unless}} />
{{/each}}

Demo: http://jsfiddle.net/ambiguous/PHKps/1/

Of course, picking out any other index is harder and leaves you either modifying the input data (as before) or adding some sort of {{#if_eq}} custom helper.



回答2:

index will be passed as second argument,

<form>
    {{#each people as |value index|}}
        <input value="{{value}}" type="radio" {{#unless index}}checked="checked"{{/unless}}/>
     {{/each}}
</form>