6

So, I found that array elements can be accessed in Handlebars using:

{{myArray.2.nestedObject}} and {{myArray.0.nestedObject}}

..to get the third and first elements for instance. (handlebars-access-array-item)

Is there a way to get the last element from an array? I tried creating a helper for it:

Handlebars.registerHelper("lastElement", function(array) {
  return array.last();  //Array.prototype extension
});

...and calling it as follows in the template:

{{lastElement myArray}} or even {{lastElement myArray.lastElement nestedArray}}

Sadly, this doesn't work. Helper functions return strings apparently. What I need is a way to be able to do this even with multi-dimensional arrays.

Community
  • 1
  • 1
Sephie
  • 331
  • 1
  • 3
  • 15
  • 2
    Note that you could use `{{myArray.[2].nestedObject}}` for the first example. The [same segment-literal notation](https://github.com/wycats/handlebars-site/issues/26) might help for a variable index number? – Arjan Feb 23 '13 at 23:52

2 Answers2

7

Should work, I've tested it.

Template:

{{last foo}}

Data:

{foo : [1,2,3,4,5,6]}

Helper:

Handlebars.registerHelper("last", function(array) {
  return array[array.length-1];
});
Łukasz Jagodziński
  • 3,009
  • 2
  • 25
  • 33
-1

The above piece of code works fine in all the cases. But if the array passed if a null array, possibility of the handlebar function throwing error is there. Instead perform a null check and then return the value accordingly.

kahsyv
  • 1