#each : Iteration Helper
Iterate over arrays or collections, rendering the enclosed template for each item. The data context changes to the current item within the block.
On this page
Syntax
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
collection |
Array/IEnumerable | Yes | The collection to iterate over |
Special Variables
| Variable | Description |
|---|---|
@index |
Zero-based index of current item (0, 1, 2, …) |
@first |
Boolean, true for the first item |
@last |
Boolean, true for the last item |
this |
Reference to the current item |
../ |
Access parent context |
Examples
Basic Iteration
Data:
doc.Params["model"] = new {
items = new[] { "Apple", "Banana", "Orange" }
};
Output:
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Orange</li>
</ul>
With Object Properties
Data:
doc.Params["model"] = new {
products = new[] {
new { name = "Widget", price = 19.99m },
new { name = "Gadget", price = 29.99m }
}
};
Using Special Variables
Accessing Parent Context
Underlying Implementation
The {{#each}} helper compiles to the following Scryber template element:
<template data-bind="{{collection}}">
<!-- Your content here with {{this}} context -->
</template>
This uses Scryber’s ForEach component internally, which provides the iteration and context management.
Notes
- Empty arrays render nothing (no error)
- Works with any IEnumerable collection
- Can be nested for multi-dimensional data
- Context changes to current item within the block
- Use
{{.}}to reference the entire current item - Provides
@index,@first, and@lastspecial variables