自定义组件具有多个类似于产量的部分

rom*_*man 13 handlebars.js ember.js

我正在尝试创建一个包含多个内容部分的ember.js组件.表达期望的直观方式是使用语义子组件,该语义子组件稍后将在适当的位置呈现,以便例如

{{data-table …}}
  {{column name="Name" … }}}
    item.name
  {{/column}}
  ...
{{/data-table}}
Run Code Online (Sandbox Code Playgroud)

将转变为

<table …>
  <thead>
    <th>Name</th>
    ...
  </thead>
  <tbody>
    <tr>
      <td>First item name</td>
      …
    </tr>
    ...
  </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

是否可以在handlebars.js或ember.js中实现这样的结构,例如通过把手助手?如果是这样的话?

ala*_*ani 4

解决此问题的一种方法是为您想要的每个“子组件”使用多个车把助手。

所以这是我构建应用程序的方式:

  • 在您的 app/components 目录中添加 data-table.js 文件
  • 在您的 app/templates/components 目录中添加 data-table.hbs 文件
  • 在您的 app/helpers 目录中添加一个名为 custom_views.js 的自定义视图文件

无论您在哪里调用组件,都可以向其传递参数,这些参数可能来自您的模型/控制器,类似于:

{{ data-table items=itemsArrayFromController }}
Run Code Online (Sandbox Code Playgroud)

现在变量 itemsArrayFromController 将可用于您的组件范围(即在 data-table.js 文件和 data-table.hbs 文件中)

在 data-table.js 文件中,您还可以指定组件有权访问的其他变量,因此您可能需要执行以下操作:

App.DataTableComponent = Ember.Component.extend({
  headers: ['Name', 'Some other Property']
});
Run Code Online (Sandbox Code Playgroud)

然后在 data-table.hbs 文件中,您可以渲染组件的 html 并使用助手来渲染组件的特定部分:

<table>
{{ dataTableHeaderHelper headers }}
  <tbody>
  {{#each itemsArrayFromController }}
    {{ dataTableRowsHelper item }}
  {{/each }}
  </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

因此,这里我们使用 dataTableHeaderHelper 来渲染表头,然后循环遍历 items 数组中的每个项目并为其渲染一行。

然后从您的帮助程序中生成实际的表。因此,在您的 custom_views.js 文件夹中,您可以执行以下操作:

// Returns the html for a table header
Ember.Handlebars.helper('dataTableHeaderHelper' function(headers) {
  var html = "<thead><tr>";
  for (var i = 0; i < headers.length; i++) {
    html += "<th>" + Handlebars.Utils.escapeExpression(header[i]) + "</th>";
  }
  var html += "</tr></thead>";
  return new Handlebars.Safestring(html);
}); 

// Returns the HTML for a table row
Ember.Handlebars.helper('dataTableRowsHelper' function(rows) {
  // Okay I think you get the hang of it, loop through each row
  // and then for each item generate the table row HTML
});
Run Code Online (Sandbox Code Playgroud)

这应该对你有用!