Moe-js v0.3

Rendering Collections

To loop over a collection of items, use the {{#each}} directive and the special loop variable item:

{{#each ["apples", "pears", "bananas"]}}

You can also specify a name for the loop variable. This can be handy when working with nested loops.

{{#each u in model.Users}}
{{#each r in u.roles}}
<p>Name: {{}} Role: {{r}}</p>

When iterating over an object, the loop variable has two properties .key and .value:

{{#each fruit in { "apples": "red", "bananas": "yellow" } }}
<p>Fruit: {{fruit.key}} Color: {{fruit.value}}

Inside the {{#each}} statement, a special variable scope is also available:

    index: 0,             // The index of the currently rendering item
    item: 'Apples',       // The currently rendering item
    items: [              // An array of all items being iterated
    first: true,          // True if the current item is the first item
    last: true,           // True if the current item is the last item
    outer: {}             // Reference to the next outer loop scope (if nested looping)

This lets you do things like:

{{#each User}}
{{#if scope.first}}<hr />{{/if}}
{{#if scope.last}}<p> -- END -- </p>{{/if}}

You can also do odd/even rendering with {{#if item.index % 2}} etc...

{{#each}} blocks can also have an {{#else}} clause that will be rendered if the collection is empty:

{{#each model.user}}
<p>No Users Found :(</p>

Subscribe for more like this. No spam, just fun tech stuff :)

Or, find me on Twitter: @toptensoftware.