使用handlebars.js模板以数组中的最后一项为条件

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)

  • {{#unless @last}},{{/ unless}} FTW! (21认同)

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)

  • 很好的答案,但我确实注意到一个挂断.如果数组中的项是字符串或任何其他原语,则无法向其追加属性.我的解决方法是使用item的值创建一个新字符串,它在技术上是一个对象,并将属性附加到该字符串,如下所示:[https://gist.github.com/jordancooperman/5440241 ](https: //gist.github.com/jordancooperman/5440241) (5认同)
  • 当[first`和`last`为本机的答案](http://stackoverflow.com/a/19784986/1269037)更有效时,为什么接受这个答案? (3认同)
  • 惯性。这个答案是两年前写的并被接受的。具有原生结构的 Handlebars 版本于一年多前发布。我猜 OP 已经继续前进了。 (2认同)

小智 26

如果您只是尝试处理数组的第一项,这可能会有所帮助

{{#each data-source}}{{#if @index}},{{/if}}"{{this}}"{{/each}}

@index由每个帮助程序提供,对于第一个项目,它将等于零,因此可以由if帮助程序处理.

  • 对于那些发现这个并且希望在[Meteor](http://meteor.com)的Handlebars实现中使用它的人来说,这是不可行的.@打破了一切. (7认同)
  • 简单而优雅! (3认同)