【问题标题】:Simple way to create a grid with Handlebars.js?使用 Handlebars.js 创建网格的简单方法?
【发布时间】: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


【解决方案1】:

所以,模板应该是:

<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/

【讨论】:

  • Šime,谢谢。数据来自 Spine.js 模型。为了将数据和表示分开,我尝试完全使用视图代码(即模板和帮助器 fn,如果需要)来呈现数据。
  • @Adam 你能用你的数据结构更新你的问题吗?是二维数组吗?
  • @Adam 好的,我已经更新了答案以反映新信息。
【解决方案2】:

尝试使用表格标签示例:

<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 和类作为它们的属性,以便于操作策略。

【讨论】:

  • 需要比表格更大的灵活性,尽管这不是重点。这个答案不使用把手,这是主要挑战。网格的 CSS 已经可以使用了。
  • @Adam 更灵活?你能详细说明一下吗?
  • @Šime 表格不允许像单元格重叠这样的视觉效果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-03
  • 1970-01-01
  • 1970-01-01
  • 2023-01-26
  • 1970-01-01
相关资源
最近更新 更多