我想获取我的JSON文件的最后一项。所以我看了Getting the last element from a JSON array in a Handlebars template并尝试实现它。到目前为止,它给了我最后一个条目的数量,但我也需要选项,但不知道该怎么做?
这是来自提到的例子
Handlebars.registerHelper("last", function(array, options) {
return array[array.length-1];
});
我试着这样做:
Handlebars.registerHelper("last", function(array, options) {
if (array[array.length-1]) return options.fn(this);
return options.inverse(this);
});
我的JSON文件结构是:
releases: [{
"title" : "some title",
"releaseDate" : "2014-08-04"
},
"services": [{
"name" : "spotify",
"link" : "some link"
},
{
"name" : "itunes",
"link" : "some link"
}]
]
所以我的Handlebars模板看起来像:
{{#each releases}}
{{#last releaseDate}}
{{#each services}}
{{#equal name "Spotify" }}
<a href="{{link}}"></a>
{{/equal}}
{{#equal name "Itunes" }}
<a href="{{link}}"></a>
{{/equal}}
{{/each}}
{{/last}}
{{/each}}
但它不起作用,它显示一个空的DIV
请帮帮忙?
答案 0 :(得分:6)
句柄已有@first
和@last
个伪变量。请参阅iterations和built-in helpers上的文档。
示例用例:
textArray = ["First", "N-1", "Last"]
<span>{{#each textArray}}{{#if @last}}{{this}}{{/if}}{{/each}}</span>
结果:<span>Last</span>
答案 1 :(得分:0)
我会为此使用迭代器助手。
Handlebars.registerHelper('layoutReleases', function (rows, options) {
var buffer = [], lastRow;
if (rows && rows.length > 0) {
lastRow = rows[rows.length-1];
buffer.push(options.fn(lastRow));
}
return buffer.join('');
});
模板:
{{#layoutReleases releases}}
{{releaseDate}}
{{#each services}}
{{#equal name "Spotify" }}
<a href="{{link}}"></a>
{{/equal}}
{{#equal name "Itunes" }}
<a href="{{link}}"></a>
{{/equal}}
{{/each}}
{{/each}}