我的应用程序上的GET操作返回数组中的数据:
Value":[{"Id":"6b7","Notes":"testing","CreatedBy":"User1"},{"Id":"6b7","Notes":"Testing 1","CreatedBy":"User2"}]
我使用上面的方法来填充模板:
<div class="create-note">
<form>
**<input type="hidden" id="Id" name="Id" value="{{this.Value.Id}}" />**
<textarea id="Notes" name="Notes"></textarea>
<button for="" type="submit" class="btn btn-primary ">Add Note</button>
<button type="reset" class="btn">Cancel</button>
</form>
{{#unless this.Value.length}}
<div class="alert alert-info">Notes do not exist.</div>
{{else}}
<table class="table">
<thead>
<tr>
<th style="text-align:left">Note</th>
<th style="text-align:left">Created By</th>
</tr>
</thead>
<tbody>
{{#each this.Value}}
<tr>
<td>
{{this.Notes}}
</td>
<td>
{{this.CreatedBy}}
</td>
</tr>
{{/each}}
</tbody>
</table>
{{/unless}}
</div>
如何填充隐藏的表单字段(Id)。 value = {{this.Value.Id}}不起作用,因为我们有一个数组。
答案 0 :(得分:2)
在JavaScript中拉出Id
并将其放在您想要的位置:
var data = {
"Value": [
{"Id": "6b7", "Notes": "testing", "CreatedBy": "User1"},
{"Id": "6b7", "Notes": "Testing 1", "CreatedBy": "User2"}
]
};
data.Id = data.Value[0].Id;
var tmpl = Handlebars.compile($('#template').html());
var html = tmpl(data);
然后在模板中引用{{this.Id}}
(或只是{{Id}}
)。
演示:http://jsfiddle.net/ambiguous/WSAxn/
或者,添加一个可以挖掘出价值的帮助器,但这似乎是不必要的复杂性。
如果您打算使用Handlebars,您必须习惯将数据按摩到Handlebars友好的表格中。 Handlebars的简单性既有优点也有缺点。