The {{this}} expression references the current context within a block helper. Inside a #each block iterating over an array, {{this}} refers to the current array element. Inside a #each block iterating over an object, {{this}} refers to the current key's value.
Syntax
{{this}}
Or to access a property of the current element:
{{this.fieldName}}
Examples
Iterate over a simple array
{{#each people}}{{this}}; {{/each}}
Input:
{ "people": ["Gilfoyle", "Bachman", "Yang"] }
Output: Gilfoyle; Bachman; Yang;
{{this}} refers to each string element in the people array in turn.
Access a property of each object in an array
{{#each orders}}{{this.id}}: {{this.item}}
{{/each}}
Input:
{
"orders": [
{ "id": 1, "item": "Widget" },
{ "id": 2, "item": "Gadget" },
{ "id": 3, "item": "Doohickey" }
]
}
Output:
1: Widget 2: Gadget 3: Doohickey
{{this}} refers to each object in the orders array. Use dot-notation (this.fieldName) to access individual properties of the current object.
Iterate over the key-value pairs of an object
{{#each record}}{{@key}}: {{this}}
{{/each}}
Input:
{
"record": {
"firstName": "Charles",
"lastName": "Dickens",
"title": "A Tale of Two Cities"
}
}
Output:
firstName: Charles lastName: Dickens title: A Tale of Two Cities
Inside a #each block iterating over an object, {{this}} refers to the value of the current key. Use {{@key}} to reference the key name alongside it.
Use #each this to iterate over a nested array
{{#with data}}
{{#each this}}{{this.name}} (id: {{this.id}})
{{/each}}
{{/with}}
Input:
{
"data": [
{ "name": "John", "id": 1 },
{ "name": "Leslie", "id": 2 }
]
}
Output:
John (id: 1) Leslie (id: 2)
After #with data shifts the context to the data array, {{#each this}} iterates over its elements. {{this}} then refers to each object in that array.
Usage notes
-
{{this}}always refers to the current context -- what it resolves to depends on what is being iterated. - When iterating over an array of strings or numbers,
{{this}}returns the element value directly. - When iterating over an array of objects, use
{{this.fieldName}}to access individual properties. - When iterating over an object's key-value pairs,
{{this}}returns the value of the current key. Use{{@key}}for the key name. - Use
{{#each this}}to iterate over elements when the current context is already an array (for example, after a#withblock).