【发布时间】:2012-02-14 01:20:14
【问题描述】:
我正在尝试从这个数组中的对象生成一个由五个元素组成的 div 网格:
[{n:'a'},{n:'b'},{n:'c'},{n:'d'}...{n:'y'}];
该数组可能包含 1 到 50 个对象,数据格式是来自 Spine.js 模型的一维数组。为了分离数据和表示,我希望将数据保存在一个 1d 数组中,并使用视图(车把模板)代码在每 5 个项目上开始一个新行,如下所示:
<div class="grid">
<div class="row">
<div class="cell"> a </div>
<div class="cell"> b </div>
<div class="cell"> c </div>
<div class="cell"> d </div>
<div class="cell"> e </div>
</div>
<div class="row">
<div class="cell"> f </div>
etc...
</div>
我有一个解决方案,方法是在辅助函数中返回整个字符串。只有我的模板看起来像:
<script id="grid-template" type="text/x-handlebars-template">
{{#grid}}
{{/grid}}
</script>
这似乎违背了使用模板的意义。有没有一种简单的方法来创建像上面这样的网格,代码主要位于模板中?
[编辑]解决方案
根据@Sime 下面的回答修改控制器中的数据。
模板代码:
<script id="grid-template" type="text/x-handlebars-template">
{{#rows}}
<div class="row">
{{#cells}}
<div class="cell">
{{n}}
</div>
{{/cells}}
</div>
{{/rows}}
</script>
控制器渲染代码():
this.data=[{n:'a'},{n:'b'},{n:'c'},{n:'d'}...{n:'y'}]; // previously set
this.rows=[];
var step=5,
i=0,
L=this.data.length;
for(; i<L ; i+=step){
this.rows.push({cells:this.data.slice(i,i+step)});
};
this.el.html(this.template(this));
【问题讨论】:
-
单元格的宽度和高度是否相同?
标签: javascript templates handlebars.js