英文原文:http://emberjs.com/guides/templates/displaying-a-list-of-items/

显示项目列表(Displaying a List of Items)

If you need to enumerate over a list of objects, use Handlebars’ {{#each}} helper:

如果你需要枚举一个对象列表,可以使用Handlebar{{#each}}助手:

  1. <ul>
  2. {{#each people}}
  3. <li>Hello, {{name}}!</li>
  4. {{/each}}
  5. </ul>

The template inside of the {{#each}} block will be repeated once for each item in the array, with the context of the template set to the current item.

对于数组中的每一个对象,{{#each}}块内的模板都会被执行一次,模板的内容将被对象的值所代替。

The above example will print a list like this:

上面的例子将会输出如下所示的一个列表:

  1. <ul>
  2. <li>Hello, Yehuda!</li>
  3. <li>Hello, Tom!</li>
  4. <li>Hello, Trek!</li>
  5. </ul>

Like everything in Handlebars, the {{#each}} helper is bindings-aware. If your application adds a new item to the array, or removes an item, the DOM will be updated without having to write any code.

Handlebars的所有东西一样,{{#each}}助手也具有绑定机制。如果应用程序为数组增加一个对象,或删除一个对象, DOM将自动更新而不需要写任何其他代码。

There is an alternative form of {{#each}} that does not change the scope of its inner template. This is useful for cases where you need to access a property from the outer scope within the loop.

{{#each}}助手还有一个可选的语法形式,这种形式不会改变内部模板的作用域。如果你需要从循环内的外部空间访问一个属性,这个语法很有用。

  1. {{name}}'s Friends
  2. <ul>
  3. {{#each friend in friends}}
  4. <li>{{name}}'s friend {{friend.name}}</li>
  5. {{/each}}
  6. </ul>

This would print a list like this:

上面语句将输出这样一个列表:

  1. Trek's Friends
  2. <ul>
  3. <li>Trek's friend Yehuda</li>
  4. <li>Trek's friend Tom!</li>
  5. </ul>

The {{#each}} helper can have a matching {{else}}. The contents of this block will render if the collection is empty:

{{#each}}助手也可以使用{{else}}助手。如果集合为空,这个块的内容就会被渲染。

  1. {{#each people}}
  2. Hello, {{name}}!
  3. {{else}}
  4. Sorry, nobody is here.
  5. {{/each}}