有条件使用handlebars.js模板阵列最后一个项目 [英] conditional on last item in array using handlebars.js template

查看:178
本文介绍了有条件使用handlebars.js模板阵列最后一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我利用handlebars.js我的模板引擎,我期待作出有条件段显示,只有当它在阵列中包含的模板配置对象中的最后一个项目。

  {
  列:[{< OBJ>},{< OBJ>},{< OBJ>},{< OBJ>},{< OBJ>}]
}

我已经拉到一个辅助做一些平等/大于/小于比较和已经成功确定最初的项目这种方式,但有没有运气访问我的目标数组的长度。

  Handlebars.registerHelper('比较',函数(左值,右值,期权){...}){{#each_with_index列}}+
< D​​IV CLASS ='{{#等于索引0}}第{{/等于}} {{#等于指数../ columns.length()}}最后{{/等于}}'>中+
< / DIV>中+
{{/ each_with_index}}

有谁知道一个快捷方式,不同的方法,有的车把善良,将让我不必撕到handlebars.js引擎,以确定最好?


解决方案

  

2013年11月,更好的东西被内置在车把。这个
  答案是不再需要。请参见雅各面包车林根的
  回答



有一个快速的帮助我写了这样的伎俩是:

  Handlebars.registerHelper(的foreach功能(ARR,期权){
    如果(options.inverse&安培;&安培;!arr.length)
        返回options.inverse(本);    返回arr.map(功能(项指数){
        。项目$指数=指数;
        。项目$第一=指数=== 0;
        。项目$最后=指数=== arr.length-1;
        返回options.fn(项目);
    })。加入('');
});

然后,你可以写:

  {{#的foreach富}}
    < D​​IV CLASS ='{{#如果$第一}}第{{/ if}个} {{#如果$最后}}最后{{/ if}个}'>< / DIV>
{{/的foreach}}

I am leveraging handlebars.js for my templating engine and am looking to make a conditional segment display only if it is the last item in array contained in the templates configuration object.

{
  columns: [{<obj>},{<obj>},{<obj>},{<obj>},{<obj>}]
}

I've already pulled in a helper to do some equality/greater/less-than comparisons and have had success identifying the initial item this way but have had no luck accessing my target array's length.

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}}"

Does anyone know a shortcut, different approach, and some handlebars goodness that will keep me from having to tear into the handlebars.js engine to determine best course?

解决方案

As of November 2013, something better is built in to Handlebars. This answer is no longer necessary. See Jacob van Lingen's answer.


A quick helper I wrote to do the trick is:

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

Then you can write:

{{#foreach foo}}
    <div class='{{#if $first}} first{{/if}}{{#if $last}} last{{/if}}'></div>
{{/foreach}}

这篇关于有条件使用handlebars.js模板阵列最后一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆