Articles in this section

this helper

The this keyword refers to different objects, depending on how it’s invoked (used or called).

You can use the this expression in handlebars to reference the current context. Within a block helper, this refers to the element being iterated over. While iterating an object, this refers to the complete object. While iterating an array, this refers to a complete array. We have to use {{#each this}} to refer to individual elements in an array.

Template

Context

Output

[
  {{#with data}}
    {{#each this}}
    {{#if @index}}, {{/if}}
    {
             "firstName" : {{this.name}},
      {{#each this}}
        “{{@key}}”: “{{this}}”
      {{/each}}
    }
    {{/each}}
  {{/with}}
]
{
  "data": [
    {
      "name": "John",
      "id": 1
    },
    {
      "name": "Leslie",
      "id": 2
    }
  ]
}
          [
    {
      "firstName": "John",
      "Name": "John",
      "id": 1
    },
    {
      "firstName": "Leslie",
      "name": "Leslie",
      "id": 2
    }
  ]
       

This example shows a simple dataset with two names. The first {{#each this}} references the objects in the data array. So, in this case, we’re referring to each object in the array.

{
  "data": [
    {
      "name": "John",
      "id": 1
    },
    {
      "name": "Leslie",
      "id": 2
    }
  ]
}

The second use of {{#each this}} references each element of the object. That would be the key: value pairs in each object.

{
  "data": [
    {
      "name": "John",
      "id": 1
    },
    {
      "name": "Leslie",
      "id": 2
    }
  ]
}

The third use of {{this}} references the value of the key: value pair.

{
  "data": [
    {
      "name": "John" ,
      "id":  1 
    },
    {
      "name":  "Leslie" ,
      "id":  2
    }
  ]
}

So, the final output would be

[
    {
      "name": "John",
      "id": 1
    },
    {
      "name": "Leslie",
      "id": 2
    }
  ]