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

后端 未结 2 1618
难免孤独
难免孤独 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];
    });
    

提交回复
热议问题