javascript - 用 Handlebars 搭建动态 table

标签 javascript html handlebars.js

我正在尝试使用 handlebars.js 创建一个动态表。 我想放入表中的对象示例是:

Object { title: "The Room", director: "Tommy Wiseau", genre: "Drama?", rating: "1"}

我想要的 HTML:

    <thead>
    <th>Title</th>
    <th>Director</th>
    <th>Genre</th>
    <th>Rating</th>
    <th>Edited</th>
  </thead>
  <tbody>
    <tr>
      <td>The Room</td>
      <td>Tommy Wiseau</td>
      <td>Drama?</td>
      <td>1</td>
      <td>2017-05-16</td>
    </tr>
  </tbody>

我的问题是用户也可以添加他们自己的表格标题,所以我不能这样做:

<td>{{title}}</td>

它必须动态完成。我看过:{{#each}},但似乎无法理解它。另外,我如何打印属性名称而不是对象中的值(就像我想要在表标题中一样)。

  <thead>
    {{#each data}}
    <th>{{@key}}</th><!--property name here-->
    {{/each}}
  </thead>
  <tbody>
    {{#each data}}
    <tr>
      <td>{{this}}</td><!--property value here-->
    </tr>
    {{/each}}
  </tbody>

这是我的模板。我觉得我正在接近正确的解决方案,但我不确定我哪里做错了。

$.getJSON("php/loadItems.php?category=" + selected, function(data) {
    let source = $("#itemTemplate").html();
    let template = Handlebars.compile(source);
    delete data[0].id
    $("#tableContainer").append(template(data));
  });

这就是我在 JS 中处理数据的方式。非常感谢任何帮助!

最佳答案

根据您的描述,我认为您别无选择,只能通过遍历数组中的每个对象并过滤掉所有表头(对象键)重复项。换句话说,您必须从所有数据对象中构建一个包含所有唯一 键的数组,这些键将用作表中的列标题。你可以使用现有的库来帮助你做到这一点,比如 Underscore's .uniq ,但我将提供一个示例实现:

var uniqueKeys = data.reduce(function (acc, obj) {
    return acc.concat(Object.keys(obj).filter(key => acc.indexOf(key) === -1));
}, []);

接下来,我们必须将我们的唯一键数组传递给我们的模板。唯一键将用于创建表标题以及 lookupdata 中每个对象的操作.

template({
    uniqueKeys: uniqueKeys,
    data: data
});

我们的模板必须更新为以下内容:

<thead>
    <tr>
        {{#each uniqueKeys}}
            <th>{{this}}</th>
        {{/each}}
    </tr>
</thead>
<tbody>
    {{#each data}}
        <tr>
            {{#each ../uniqueKeys}}
                <td>{{lookup .. this}}</td>
            {{/each}}
        </tr>
     {{/each}}
</tbody>

请注意 {{lookup .. this}} 行是说,“在 data 中使用此键名称的属性呈现 uniqueKeys 中当前对象的值。

另请注意,我添加了 <tr> <thead> 中的标签.根据MDN , 这些是 <thead> 中唯一允许的标签.

我创建了一个 fiddle供引用。

关于javascript - 用 Handlebars 搭建动态 table ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44002447/

相关文章:

javascript - Angular.JS : cannot set default route when no hash

javascript - 使用 jquery 删除数组

node.js - ../this在父级和子级具有相同值时在内部循环内返回 View 对象

javascript - 将 PHP 应用程序编译为具有变体的 HTML

forms - 如何修复 TypeError : Cannot read property 'name' from Express Nodemailer

javascript - 如何在 Firestore JS 中获取现有的文档 key ?

javascript - Django提交表单->重定向到新页面->自动更新新页面

javascript - HTML 中是否存在属性节点?

javascript - 如何使用 JQuery 和 Rails 创建类似 Wufoo(表单生成器)的 Web 应用程序?

javascript - 禁用按钮直到字段已满纯JS