meteorhandlebars.jsspacebars

How to access final element in Handlebars.js array?


Given the following data structure:

{
    "name" : "test",
    "assetType" : "Home",
    "value" : [ 
        {
            "value" : "999",
            "date" : "10/03/2018"
        }, 
        {
            "value" : "1234.56",
            "date" : "10/04/2018"
        }
    ]
}

How can I directly access the first and last element of value in Handlebars? My code is:

<td>{{value.[0].value}}</td>
<td>{{value.[value.length - 1].value}}</td>

The first statement works fine, but I cannot figure out how to access the last element. value.length inside the []'s does not return any value, but rendering value.length outside of the array works fine.

I tried using @first and @last in the array but those don't seem to work either.


Solution

  • As already pointed out, you can easily solve this with a template helper:

    Template.myTemplate.helpers({
      first (arr) {
        return arr && arr[0]
      },
      last (arr) {
        return arr && arr[arr.length - 1]
      },
      atIndex (arr, index) {
        return arr && index >= 0 && index <= arr.length - 1 && arr[index]
      }
    })
    

    You can then create a context using #with where the context object is the result of the helpers. Inside this context you can access properties using this.

    Accessing values with the name value would look like the following:

    <td>{{#with first value}}{{this.value}}{{/with}}</td>
    <td>{{#with last value}}{{this.value}}{{/with}}</td>
    <td>{{#with atIndex value 5}}{{this.value}}{{/with}}</td>