有没有办法在 ember 车把模板中定义和迭代数组?

Is there a way to define and iterate over an array in ember handlebars templates?

我正在编写样式指南,需要遍历车把模板中的数组。

我知道您可以在传递给模板时迭代对象或其他变量,但是有没有办法迭代模板中定义的集合?我认为这打破了 handlebars 推动的 "no-logic in views" 概念,但我想这是一个常见的用例。

{{#each ['success', 'warning', 'error', 'info'] key="@index" as |type|}}
  <div class='banners-container'>
    <div class='content'>
      <div class='banner banner-{{type}} has-icon has-dismiss'>
        <p>Banner {{type}}</p>
      </div>
    </div>
  </div>
{{/each}}

我希望这会输出 4 个 banners-container 元素的集合,但它没有输出任何内容。

处理此用例的最佳方法是什么?

您可以在 controller/component 文件中定义数组并在 hbs 中使用该 property。说

app/controllers/application.js

import Controller from '@ember/controller';
import { A } from '@ember/array';

export default Controller.extend({
  status: A(['success', 'warning', 'error', 'info']),
})

在你的 app/templates/application.hbs

{{#each status as |type|}}
  {{type}}
{{/each}}

你可以看看ember native array function

您可以使用array helper from ember-composable-helpers直接在模板中组合数组:

{{#each (array 1 2 3) as |numbers|}}
  {{numbers}}
{{/each}}