我已经在这里工作了好几个小时,我仍然没有想到这一点。非常感谢任何帮助。
我有这个模板
<script id="TwoLevelsDeepTbodyTemplate" type="text/x-jsrender">
<tbody class="TwoLevelsDeep">
{{for #data}}
<tr class="ClassificationTwoLevelsDeep">
<td colspan="2">┖ <span class="Type">{{:title}}</span></td>
<td class="CusClassificationInput">
<span class="Editable hidden"><input type="text" value="{{:percentageOfBusiness}}" maxlength="3">%</span>
<span class="CustomerTypeValue">
{{if percentageOfBusiness}}
{{:percentageOfBusiness}}
{{else}}
-
{{/if}}
</span>
</td>
</tr>
{{/for}}
</tbody>
</script>
收集数据和填充模板的方法:
function getGrandChildrenTemplate(paryGrandChildren) {
let jsonObj = [];
$.each(paryGrandChildren, function (i, gc) {
let item = {};
item['title'] = gc.Text;
item['percentageOfBusiness'] = gc.Data;
jsonObj.push(item);
});
let data = JSON.stringify(jsonObj);
let tmpl = $.templates('#TwoLevelsDeepTbodyTemplate');
let html = tmpl.render(data);
console.log(data);
console.log(html);
return html;
};
当我检查日志时,模板看起来像
<tbody class="TwoLevelsDeep">
<tr class="BCClassificationTwoLevelsDeep">
<td colspan="2">┖ <span class="Type"></span></td>
<td class="CusClassificationInput">
<span class="Editable hidden"><input type="text" value="" maxlength="3">%</span>
<span class="CustomerTypeValue">-</span>
</td>
</tr>
</tbody>
字符串化的JSON如下所示:
[{"title":"Single Family","percentageOfBusiness":""},{"title":"Multi-Family","percentageOfBusiness":""}]
请注意,模板中没有任何内容应该填充值。此外,在此示例中应该有2只有一个TR。我显然做错了什么,但我无法弄清楚是什么。我对{{for #data}}的理解是它(在这个例子中)将为每个对象创建一个TR并根据键填充值。这不正确吗?
答案 0 :(得分:1)
2次更改
使用{{for data}}进行迭代 前
<script id="TwoLevelsDeepTbodyTemplate" type="text/x-jsrender">
<tbody class="TwoLevelsDeep">
{{for data}}
<tr class="ClassificationTwoLevelsDeep">
<td colspan="2">┖ <span class="Type">{{:title}}</span></td>
<td class="CusClassificationInput">
<span class="Editable hidden"><input type="text" value="{{:percentageOfBusiness}}" maxlength="3">%</span>
<span class="CustomerTypeValue">
{{if percentageOfBusiness}}
{{:percentageOfBusiness}}
{{else}}
-
{{/if}}
</span>
</td>
</tr>
{{/for}}
</tbody>
</script>
无需对json数据进行字符串化
function getGrandChildrenTemplate(paryGrandChildren) {
let jsonObj = [];
$.each(paryGrandChildren, function(i, gc) {
let item = {};
item['title'] = gc.Text;
item['percentageOfBusiness'] = gc.Data;
jsonObj.push(item);
});
let tmpl = $.templates('#TwoLevelsDeepTbodyTemplate');
let html = tmpl.render({
data: jsonObj
});
console.log(html);
return html;
};