Getting the last element from a JSON array in a Handlebars template

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

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

.. to obtain, for example, the third and first elements. ( handlebars-access-array-item )

Is there a way to get the last element from an array? I tried to create an assistant for him:

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

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

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

Unfortunately this does not work. Helper functions seem to return strings. I need a way to do this even with multidimensional arrays.

+5
source share
2 answers

Should work, I tested it.

Template:

{{last foo}}

Data:

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

Helper:

Handlebars.registerHelper("last", function(array) {
  return array[array.length-1];
});
+7
source

. , . , .

-1

All Articles