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

后端 未结 2 1620
难免孤独
难免孤独 2021-01-12 19:23

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

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

..to get the

相关标签:
2条回答
  • 2021-01-12 19:41

    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];
    });
    
    0 讨论(0)
  • 2021-01-12 19:43

    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.

    0 讨论(0)
提交回复
热议问题