[] : Indexer
Reads an item from an array or list by its position, or from a dictionary by its key.
On this page
Syntax
{{collection[index]}}
{{dictionary["key"]}}
{{dictionary[expression]}}
Arrays and lists
The index is zero based - the first item is [0].
Data:
builder.WithData("model", new {
items = new[] {
new { name = "Widget", price = 10.0 },
new { name = "Gadget", price = 15.5 }
}
});
Template:
<p>{{model.items[0].name}}</p>
<p>{{model.items[1].price}}</p>
Output:
Widget
15.5
Dictionaries
A dictionary is read with its key in quotes, or with an expression that gives the key.
Data:
builder.WithData("model", new {
currency = "EUR",
rates = new Dictionary<string, double> { ["GBP"] = 1.0, ["EUR"] = 1.17 }
});
Template:
<p>{{model.rates["GBP"]}}</p>
<p>{{model.rates[model.currency]}}</p>
Output:
1
1.17
JSON objects can be read in the same way.
Notes
- An index outside the collection, or a key that is not in the dictionary, gives no value rather than an error.
- A key in quotes reads a dictionary or JSON object. It does not read a property of a C# object - use the property access
.for those. - The index can be any expression, e.g.
{{model.items[count(model.items) - 1].name}}for the last item.