English 中文(简体)
从处理栏模板中的 JSON 阵列获取最后一个元素
原标题:Getting the last element from a JSON array in a Handlebars template

因此,我发现阵列元素 可以用手持栏访问 使用:

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

(handlebars-access-array-items )

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

...在模板中称它如下:

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

可悲的是,这不起作用。 助手的函数显然返回字符串。 我需要的是能够做到这一点的方法, 即使是多维的阵列。

问题回答

应该有用,我测试过了

模板 :

{{last foo}}

数据 :

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

帮助者 :

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

上述代码部分在所有实例中都运作良好。 但如果数组在一空数组时通过, 可能会发生手控栏投掷错误。 相反, 执行一个空检查, 然后相应返回数值 。





相关问题
JQuery/MVC Search Issue

I have inherited a piece of work where the entry screen shows a summary of 20 calculated variables. E.g. Var A (250), Var B (79). Clicking on any of these links takes the user to a view with a ...

jQuery quicksearch plug-in tinkering with JSON

I ve implemented the quicksearch plugin by Rik Lomas and I love it for an application in a custom CMS I m building. I was wondering though, since I m going to have a bizillion items in the table if ...

JSON with classes?

Is there a standardized way to store classes in JSON, and then converting them back into classes again from a string? For example, I might have an array of objects of type Questions. I d like to ...

PHP json_decode question

i m trying to use json_decode to combine a few json objects and then re-encode it. my json looks like: { "core": { "segment": [ { "id": 7, "...

Converting JSON data to Java object

I want to be able to access properties from a JSON string within my Java action method. The string is available by simply saying myJsonString = object.getJson(). Below is an example of what the string ...

热门标签