2012-07-16 65 views
7

我怎樣才能讓簡單明瞭設置第一個單選按鈕的方式在把手模板中被選中。 TKS設置第一個單選按鈕在把手模板中被選中

模板:

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

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

期望渲染:

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

感謝所有。

在車把
+0

你想從javascript代碼呈現? – 2012-07-16 03:42:45

+0

我認爲這將幫助:http://stackoverflow.com/questions/26066768/how-to-set-the-selected-item-in-a-radio-button-group-in-handlebars-template,使用塊幫手。 – zx1986 2016-09-27 15:50:19

回答

9

{{#each}}不給你訪問迭代次數或類似的東西,所以你不能做到這一點不改變你的模板和數據一點點:

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

,然後添加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 } 
]); 

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

你當然可以只設置sel: true數據數組的第一個元素:

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

演示: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 

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


更新版本的Handlebars do give you access to the index

當通過物品each循環,您可以選擇通過{{@index}}

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

參考電流環路指數爲對象的迭代,使用{{@key}}代替:

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

所以如果你使用最新的Handlebars,你可以使用th做一些特殊的事情e事實如下:

  1. 第一個@index將爲零。
  2. Zero在布爾上下文中是僞造的。

這可以讓你做到這一點:

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

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

當然,挑選出任何其他指標更硬,讓你無論是修改輸入數據(如前)或加入某種{{#if_eq}}定製助手。

+1

真的不知道,當他們執行的功能,但你可以訪問迭代器'{{#each}}'和'@ index'內的陣列和'@ key'的對象。 http://handlebarsjs.com/#iteration。 – Maroshii 2013-08-14 11:00:14

+1

@Maroshii:在1.0.0-beta6之後添加了這個東西(這是AFAIK最新的,當我回答這個問題時)。我已經添加了一個更新來說明'@ index'的東西,它在beta和最終的1.0.0之間滑動,謝謝你的提醒。 – 2013-08-14 17:56:53

+0

這幫了我很多! – zx1986 2016-09-27 15:49:42

0

index將作爲第二個參數傳遞,

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