我有一个通过Handlebars.js
模板创建的动态表,问题是我无法将 id 分配给每个单元格,将它们的位置表示为行和列。我有下面的模板,
<script id="td-template" type="text/x-handlebars-template">
{{#each ships}}
<tr>
<td class='left-aligned'>{{this.name}}</td>
<td class="default" id="id{{@index}}"></td>
<td class="default" id="id{{@index}}"></td>
<td class="default" id="id{{@index}}"></td>
<td class="default" id="id{{@index}}"></td>
<td class="default" id="id{{@index}}"></td>
<td class="default" id="id{{@index}}"></td>
<td class="default" id="id{{@index}}"></td>
<td class="default" id="id{{@index}}"></td>
</tr>
{{/each}}
</script>
第一个循环返回 0,第二个循环返回 1,反之亦然。我需要的是添加一个公式而不是{{@index}} ,但它不会让我在我打算破坏 html 或表格本身时添加。
我打开任何建议,例如JQuery
Handlebars.js
您可以定义一个辅助函数,如下所示:
var columnsCount = 3; // change this to the total number of columns per row in your table.
Handlebars.registerHelper("multiply", function(index, count){
return (index * columnsCount) + count;
});
然后使用以下内容设置 ID:
<script id="td-template" type="text/x-handlebars-template">
{{#each ships}}
<tr>
<td class='left-aligned'>{{this.name}}</td>
<td class="default" id="id{{multiply @index 1}}"></td>
<td class="default" id="id{{multiply @index 2}}"></td>
<td class="default" id="id{{multiply @index 3}}"></td>
.....
</tr>
{{/each}}
</script>
这是一个显示这种方法在行动中的片段:
var columnsCount = 3; // change this to the total number of columns per row in your table.
Handlebars.registerHelper("multiply", function(index, count){
return (index * columnsCount) + count;
});
var context = {
ships: [{
name: 'ship one'
}, {
name: 'ship two'
}]
};
$('#rendered').append(Handlebars.compile($("#td-template").html())(context));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.6/handlebars.js"></script>
<script id="td-template" type="text/x-handlebars-template">
<table>
<tbody>
{{#each ships}}
<tr>
<td class='left-aligned'>{{this.name}}</td>
<td class="default" id="id{{multiply @index 1}}">column {{multiply @index 1}}</td>
<td class="default" id="id{{multiply @index 2}}">column {{multiply @index 2}}</td>
<td class="default" id="id{{multiply @index 3}}">column {{multiply @index 3}}</td>
<!-- and so on.... -->
</tr>
{{/each}}
</tbody>
</table>
</script>
<div id="rendered"></div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句