我有一个JavaScript数组:
var personDetails = [
{firstName: "Anup", lastName: "Vasudeva", City: "Delhi"},
{firstName: "Vikas", lastName: "Kumar", City: "Banglore"},
{firstName: "Dannis", lastName: "Richie", City: "Texas"},
{firstName: "Ajay", lastName: "Sharma", City: "Pune"},
{firstName: "Deepak", lastName: "Aggarwal", City: "Delhi"},
{firstName: "Ajay", lastName: "Sharma", City: "Banglore"}
这是我打算设计的模板:
<div class="left">
<!-- Should display the first half of the rows -->
{{tmpl($data) "#someTemplate"}}
</div>
<div class="right">
<!-- Should display the rest half of the rows -->
{{tmpl($data) "#personTemplate"}}
</div>
<script id="personTemplate" type="text/x-jquery-tmpl">
{{each personDetails}}
<div class="person">
<div>${firstName}</div>
<div>${lastName}</div>
<div>${city}</div>
</div>
{{/each}}
如何操作包含行的前半部分并包含行的后半部分的数组。
编辑: 实际上,用户将按原样传递数组,并且它是模板逻辑,将数组分成两半。
感谢阅读。
答案 0 :(得分:0)
使用Array.slice将输入切成两半:
var input = [
{firstName: "Anup", lastName: "Vasudeva", City: "Delhi"},
{firstName: "Vikas", lastName: "Kumar", City: "Banglore"},
{firstName: "Dannis", lastName: "Richie", City: "Texas"},
{firstName: "Ajay", lastName: "Sharma", City: "Pune"},
{firstName: "Deepak", lastName: "Aggarwal", City: "Delhi"},
{firstName: "Ajay", lastName: "Sharma", City: "Banglore"}
];
var half_point = Math.floor(input.length / 2);
var first_half = input.slice(0, half_point);
var second_half = input.slice(half_point+1)
console.log(first_half, second_half)
我不确定你为什么要在模板本身中这样做,我建议你在数据旁边移动这个逻辑,也许是通过向Array
对象添加一个方法:
Array.prototype.chunk = function(chunk_count, chunk_no) {
var chunk_size = Math.floor(this.length / chunk_count);
return this.slice(chunk_no * chunk_size, chunk_size + chunk_no * chunk_size);
}
...并从模板的每个方法中调用它:
<script id="personTemplate" type="text/x-jquery-tmpl">
<div class="left">
{{each data.chunk(2, 0)}}
<div class="person">
<div>${firstName}</div>
<div>${lastName}</div>
<div>${city}</div>
</div>
{{/each}}
</div>
<div class="right">
{{each data.chunk(2, 1)}}
<div class="person">
<div>${firstName}</div>
<div>${lastName}</div>
<div>${city}</div>
</div>
{{/each}}
</div>
</script>
如果扩展(在其他圈子中“monkeypatching”)核心类是一个好主意,这是有争议的,你可以直接向你的input
变量添加相同的函数。
在渲染之前使用分配给模板的两个单独的变量可能会导致更少的意外,因此可能更有利于此。
答案 1 :(得分:0)
不要使用模板以这种方式操纵数据。在将用户给定的数组提供给模板之前,请在外部执行此操作。你不想这样做的原因是因为如果你留下模板来处理这样的逻辑,那么它将比在外部执行它慢得多。这对于10-20个项目的数组来说不是不可能的,但是如果数组由于某种原因变大,那么模板会慢得多。