问题
The GET operation on my application returns the data in an array:
Value":[{"Id":"6b7","Notes":"testing","CreatedBy":"User1"},{"Id":"6b7","Notes":"Testing 1","CreatedBy":"User2"}]
I use the above to populate a template:
<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>
How do I populate the hidden form field (Id). value={{this.Value.Id}} doesn't work because we have an array.
回答1:
Pull the Id
out in JavaScript and put it where you want it:
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);
And then refer to {{this.Id}}
(or just {{Id}}
) in your template.
Demo: http://jsfiddle.net/ambiguous/WSAxn/
Alternatively, add a helper that can dig the value out but that's seems like unnecessary complexity.
You have to get used to massaging your data into a Handlebars-friendly form if you're going to use Handlebars. The simplicity of Handlebars has both advantages and drawbacks.
来源:https://stackoverflow.com/questions/12520939/populating-a-hidden-form-field