#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, Dictionary or object | Yes | The collection to iterate over, or a dictionary or JSON object to iterate the entries of |
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 |
@key |
The key of the current entry (dictionary or object), or the index (collection) |
this |
Reference to the current item |
../ |
Access parent context |
Examples
Basic Iteration
Data:
builder.WithData("model", new {
items = new[] { "Apple", "Banana", "Orange" }
});
Output:
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Orange</li>
</ul>
With Object Properties
Data:
builder.WithData("model", new {
products = new[] {
new { name = "Widget", price = 19.99m },
new { name = "Gadget", price = 29.99m }
}
});
Using Special Variables
Iterating a Dictionary or Object
From 9.8, {{#each}} over a dictionary, or a JSON object (Newtonsoft JObject or System.Text.Json), runs once for each entry. this is the value, and @key is the key or property name.
Before 9.8 a dictionary or JSON object was bound once, with the whole object as
this. To bind an object once now, use{{#with}}.
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,@lastand@keyspecial variables - Iterates the entries of a dictionary or JSON object (9.8 onwards)