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

穿精又带淫゛_ 提交于 2019-12-01 03:12:56

问题


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.


回答1:


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];
});



回答2:


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.



来源:https://stackoverflow.com/questions/10755092/getting-the-last-element-from-a-json-array-in-a-handlebars-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!