2013-03-01 87 views
17

在车把,说我有names收集我该怎么办柜台车把#each

{{#each names}} 
{{position}} 
{{name}} 
{{/each}} 

其中对于第二个名字等做{{位置}}为1头名,2我绝对必须将这个位置作为收藏中的一把钥匙存放起来?

回答

2

虽然你无法对任何原生Handlebars帮手做到这一点,但你可以创建自己的。您可以拨打Handlebars.registerHelper(),传递一个字符串,其中包含您想匹配的名称(位置),以及一个将返回当前位置计数的函数。您可以跟踪关闭的位置编号,您可以拨打registerHelper。以下是一个如何注册名为position的助手的例子,该助手应该与您的模板示例一起使用。

的JavaScript:

// Using a self-invoking function just to illustrate the closure 
(function() { 
    // Start at 1, name this unique to anything in this closure 
    var positionCounter = 1; 

    Handlebars.registerHelper('position', function() { 
     return positionCounter++; 
    }); 

    // Compile/render your template here 
    // It will use the helper whenever it seems position 
})(); 

这里是一个的jsfiddle证明:http://jsfiddle.net/willslab/T5uKW/1/

虽然佣工在handlebarsjs.com记录,这花了一些努力,我要弄清楚如何使用它们。感谢挑战,我希望这有助于!

+0

尝试添加位置多个时间在同一个div /块 – Adrian 2017-02-17 17:01:28

29

您可以用内置的把手@index符号做到这一点:

{{#each array}} 
    {{@index}}: {{this}} 
{{/each}} 

@index会给每个项目的(从零开始)的索引给定数组英寸

请注意,对于使用带有Razor视图引擎的Handlebars的用户,您必须使用记号@@索引来避免编译错误。

更多内置的助手看到http://handlebarsjs.com/

+1

@algorithmicCoder这个答案看起来不错。对你起作用吗?为了清晰起见,请接受它。谢谢! – 2017-03-01 21:34:20

+0

这将显示“0”的名字,但OP要它显示“1”。 serg的答案注册了一个帮手来提供更完整的解决方案。 – Vaughan 2017-03-12 00:01:05

2

只有你必须使用{{@index}}

例如:

{{#.}} 
<li class="order{{@index}}"> counter: {{@index}}</li> 
{{/.}} 
1

这里是我的首选解决方案。注册一个可以自动扩展上下文以包含职位属性的助手。然后,只需使用新的块帮助器(例如#iter)而不是#each。

Handlebars.registerHelper('iter', function (context, options) { 
    var ret = ""; 

    for (var i = 0, j = context.length; i < j; i++) { 
     ret += options.fn($.extend(context[i], {position: i + 1})); 
    } 

    return ret; 
}); 

用法:

{{#iter names}} 
    {{position}} 
    {{name}} 
{{/iter}} 

改编自http://rockycode.com/blog/handlebars-loop-index/

14
Handlebars.registerHelper("counter", function (index){ 
    return index + 1; 
}); 

用法:

{{#each names}} 
    {{counter @index}} 
    {{name}} 
{{/each}} 
0

你可以从列表内指数获得价值。

{{#each list}} 
    @index 
{{/each}} 
+0

如何获取列表的长度? – 2017-05-17 12:45:14

+0

什么是用例? 如果您只是想遍历列表,那么每个函数都会完成这项工作,或者如果您想要根据长度应用其他操作,则只需注册一个辅助函数并从中返回列表的长度。 让我知道你是否在问别的事情,我无法理解或你有任何其他查询。 – 2017-05-17 14:35:23