我正在使用handlebars.js动态生成和填充表格行。
模板代码
<script id="row-template" type="text/x-handlebars-template">
{{#each .}}
<tr>
<form class="form-inline">
<td><label class="" id ="workerid">{{worker_id}} </label></td>
<td><a href="" id ="workerName">{{worker_name}}</a> </td></tr>
{{/each}}
</script>
Javascipt代码
var dataFinal = JSON.stringify(result);
var d1 = eval('(' + dataFinal + ')');
var tmpScrpt = $("#row-template").html();
var tmp = Handlebars.compile(tmpScrpt);
var html = tmp(d1);
$("#tablerowid").html(html);
对象d1的值为
Object {d: "[{"worker_id":1,"worker_name":"Shivank"}]"}
我无法在模板渲染的html中获得worker_id。
如何在模板脚本中访问它们,例如{{d.worker_id}}
请帮助。
答案 0 :(得分:5)
alert(d1.d[0].worker_id);
alert(d1.d[0].worker_name);
答案 1 :(得分:3)
模板中有错误,请参阅handlebars.js documentation
中的每个块使用{{#each d}}
代替{{#each .}}
工作代码:
$(function() {
var d1 = {
d: [{
"worker_id": 1,
"worker_name": "Shivank"
}]
}
var tmpScrpt = $("#row-template").html();
var tmp = Handlebars.compile(tmpScrpt);
var html = tmp(d1);
$("#tablerowid").html(html);
})
&#13;
<script data-require="handlebars.js@1.3.0" data-semver="1.3.0" src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.3.0/handlebars.js"></script>
<script data-require="jquery@3.0.0" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<script id="row-template" type="text/x-handlebars-template">
{{#each d}}
<tr>
<form class="form-inline">
<td>
<label class="" id="workerid">{{worker_id}}</label>
</td>
<td><a href="" id="workerName">{{worker_name}}</a>
</td>
</tr>
{{/each}}
</script>
<div id="tablerowid"></div>
&#13;