使用Handlebars.js创建网格的简单方法

Simple way to create a grid with Handlebars.js?

本文关键字:简单 方法 网格 创建 Handlebars js 使用      更新时间:2023-09-26

我正试图从这个数组中的对象生成一个由五个元素组成的div网格:

[{n:'a'},{n:'b'},{n:'c'},{n:'d'}...{n:'y'}];

数组可能包含1到50个对象,数据格式为来自Spine.js模型的1d数组。为了将数据和表示分离,我希望将数据保存在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));

所以,模板应该是:

<script id="template" type="x-handlebars-template">
    <div class="grid">
        {{#each this}}
        <div class="row">
            {{#each this}}
            <div class="cell">{{n}}</div>
            {{/each}}
        </div>
        {{/each}}
    </div>
</script>

但是,此模板需要一个二维数组,因此必须首先转换数据对象。

function transform ( arr ) {
    var result = [], temp = [];
    arr.forEach( function ( elem, i ) {
        if ( i > 0 && i % 5 === 0 ) {
            result.push( temp );
            temp = [];
        }
        temp.push( elem );
    });
    if ( temp.length > 0 ) {
        result.push( temp );
    }
    return result;
}

现场演示:http://jsfiddle.net/emfKH/3/

尝试使用表标记示例:

<table>
<thead>
<th>head 1</th>
<th>head 2</th>
<th>head 3</th>
</thead>
<tbody>
<tr>
<td>column 1</td>
<td>column 2</td>
<td>column 3</td>
</tr>
</tbody>
</table>

您还可以提供id和类作为它们的属性,以便于操作策略。