tec*_*don 70 javascript arrays templating helpers handlebars.js
我正在利用handlebars.js作为我的模板引擎,并且我希望只有当它是模板配置对象中包含的数组中的最后一项时才显示条件段.
{
columns: [{<obj>},{<obj>},{<obj>},{<obj>},{<obj>}]
}
Run Code Online (Sandbox Code Playgroud)
我已经拉了一个助手来做一些相等/更大/更少的比较,并且已经成功识别出这样的初始项目但是没有运气来访问我的目标数组的长度.
Handlebars.registerHelper('compare', function(lvalue, rvalue, options) {...})
"{{#each_with_index columns}}"+
"<div class='{{#equal index 0}} first{{/equal}}{{#equal index ../columns.length()}} last{{/equal}}'>"+
"</div>"+
"{{/each_with_index}}"
Run Code Online (Sandbox Code Playgroud)
有没有人知道一个快捷方式,不同的方法,以及一些把手的优点,这将使我不必撕裂到handlebars.js引擎,以确定最佳的课程?
Jac*_*gen 154
从Handlebars 1.1.0开始,第一个和最后一个已成为每个助手的原生.见票#483.
用法就像Eberanov的助手类:
{{#each foo}}
<div class='{{#if @first}}first{{/if}}{{#if @last}} last{{/if}}'>{{@key}} - {{@index}}</div>
{{/each}}
Run Code Online (Sandbox Code Playgroud)
bre*_*ell 104
从Handlebars v1.1.0开始,您现在可以在每个帮助程序中使用
@first
和@last
布尔值来解决此问题:
{{#each foo}}
<div class='{{#if @first}}first{{/if}}
{{#if @last}} last{{/if}}'>
{{@key}} - {{@index}}
</div>
{{/each}}
Run Code Online (Sandbox Code Playgroud)
我写的一个快速帮手就是:
Handlebars.registerHelper("foreach",function(arr,options) {
if(options.inverse && !arr.length)
return options.inverse(this);
return arr.map(function(item,index) {
item.$index = index;
item.$first = index === 0;
item.$last = index === arr.length-1;
return options.fn(item);
}).join('');
});
Run Code Online (Sandbox Code Playgroud)
然后你可以写:
{{#foreach foo}}
<div class='{{#if $first}} first{{/if}}{{#if $last}} last{{/if}}'></div>
{{/foreach}}
Run Code Online (Sandbox Code Playgroud)
小智 26
如果您只是尝试处理数组的第一项,这可能会有所帮助
{{#each data-source}}{{#if @index}},{{/if}}"{{this}}"{{/each}}
@index由每个帮助程序提供,对于第一个项目,它将等于零,因此可以由if帮助程序处理.