车把柜台#each

alg*_*der 17 javascript templates template-engine handlebars.js

在Handlebars中,我说我有一个names如何做的集合

{{#each names}}
{{position}}
{{name}}
{{/each}}
Run Code Online (Sandbox Code Playgroud)

其中{{position}}对于名字是1,对于第二个名称是2等等.我是否必须将位置存储为集合中的键?

Smi*_*mix 34

您可以使用内置Handlebars @index表示法执行此操作:

{{#each array}}
  {{@index}}: {{this}}
{{/each}}
Run Code Online (Sandbox Code Playgroud)

@index将给出给定数组中每个项目的(从零开始)索引.

对于使用带有Razor视图引擎的Handlebars的人,请注意必须使用符号@@ index来避免编译错误.

有关更多内置助手,请访问http://handlebarsjs.com/


ser*_*erg 20

Handlebars.registerHelper("counter", function (index){
    return index + 1;
});
Run Code Online (Sandbox Code Playgroud)

用法:

{{#each names}}
    {{counter @index}}
    {{name}}
{{/each}}
Run Code Online (Sandbox Code Playgroud)


Wil*_*ein 5

虽然您无法使用任何本机 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
})();
Run Code Online (Sandbox Code Playgroud)

这是一个 jsFiddle 来演示:http://jsfiddle.net/willslab/T5uKW/1/

虽然助手在handlebarsjs.com上有记录,但我花了一些功夫才弄清楚如何使用它们。感谢您的挑战,希望对您有所帮助!