在把手模板中设置第一个单选按钮

eth*_*eng 7 javascript templates handlebars.js

如何在Handlebars模板中选中设置第一个单选按钮的简单明了的方法.TKS

模板:

<form>
    {{#each this}}
        <input value="{{value}}" />
     {{/each}}
</form>
Run Code Online (Sandbox Code Playgroud)

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

期待渲染:

<form>
    <input value="val 1" checked />
    <input value="val 2" />
    <input value="val 3" />
</form>
Run Code Online (Sandbox Code Playgroud)

谢谢大家.

mu *_*ort 9

{{#each}} 在Handlebars中,您无法访问迭代编号或类似内容,因此您无法在不更改模板和数据的情况下执行此操作:

<form>
    {{#each this}}
        <input type="radio" value="{{value}}" {{#if sel}}checked="checked"{{/if}} />
    {{/each}}
</form>
Run Code Online (Sandbox Code Playgroud)

然后sel为数据添加值:

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

演示:http://jsfiddle.net/ambiguous/27Ywu/

您当然可以设置sel: true数据数组的第一个元素:

data = [ ... ];
data[0].sel = true;
var html = tmpl(data);
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/ambiguous/yA5WL/

或者,使用jQuery在获得HTML后检查第一个:

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

演示:http://jsfiddle.net/ambiguous/sPV9D/


较新版本的Handlebars可以让您访问索引:

循环遍历项目时each,您可以选择引用当前循环索引{{@index}}

{{#each array}}
  {{@index}}: {{this}}
{{/each}}
Run Code Online (Sandbox Code Playgroud)

对于对象迭代,请{{@key}}改为使用:

{{#each object}}
  {{@key}}: {{this}}
{{/each}}
Run Code Online (Sandbox Code Playgroud)

因此,如果您使用最新的Handlebars,您可以使用以下事实做一些特别的事情:

  1. 第一个@index是零.
  2. 零在布尔上下文中是假的.

这可以让你这样做:

{{#each this}}
    <input type="radio" value="{{value}}" {{#unless @index}}checked="checked"{{/unless}} />
{{/each}}
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/ambiguous/PHKps/1/

当然,选择任何其他索引更难,并且要么修改输入数据(如前所述),要么添加某种{{#if_eq}}自定义帮助程序.