【发布时间】:2013-02-15 09:51:41
【问题描述】:
在 Handlebars 中,假设我有一个 names 的集合。我该怎么办
{{#each names}}
{{position}}
{{name}}
{{/each}}
{{position}} 的名字是 1,第二个名字是 2,等等?我必须将位置作为键存储在集合中吗?
【问题讨论】:
标签: javascript templates handlebars.js template-engine
在 Handlebars 中,假设我有一个 names 的集合。我该怎么办
{{#each names}}
{{position}}
{{name}}
{{/each}}
{{position}} 的名字是 1,第二个名字是 2,等等?我必须将位置作为键存储在集合中吗?
【问题讨论】:
标签: javascript templates handlebars.js template-engine
您可以使用内置的 Handlebars @index 表示法做到这一点:
{{#each array}}
{{@index}}: {{this}}
{{/each}}
@index 将给出给定数组中每个项目的(从零开始的)索引。
请注意,对于在 Razor 视图引擎中使用 Handlebars 的人,您必须使用符号 @@index 以避免编译错误。
有关更多内置帮助程序,请参阅http://handlebarsjs.com/
【讨论】:
Handlebars.registerHelper("counter", function (index){
return index + 1;
});
用法:
{{#each names}}
{{counter @index}}
{{name}}
{{/each}}
【讨论】:
@index,我应该将它命名为augment、plusone、plus1 - 无论如何counter。不是p1,它记得我P2....
虽然您无法使用任何本机 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 上记录了帮助程序,但我花了一些精力来弄清楚如何使用它们。感谢您的挑战,希望对您有所帮助!
【讨论】:
只有你必须使用 {{@index}}
示例:
{{#.}}
<li class="order{{@index}}"> counter: {{@index}}</li>
{{/.}}
【讨论】:
这是我的首选解决方案。注册一个扩展上下文以自动包含您的位置属性的助手。然后只需使用新的块助手(例如#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}}
【讨论】:
您可以仅从列表中的索引获取值。
{{#each list}}
@index
{{/each}}
【讨论】:
当前方法,
自 Handlebars API V2 以来,它们已经包含一个 @number
它基本上是从 1 开始的迭代器的索引。
所以,这就是你可以做的。
{{#foreach names}}
{{@number}}
{{name}}
{{/foreach}}
参考:https://ghost.org/docs/api/v3/handlebars-themes/helpers/foreach/
【讨论】:
这对我有用
{{#each posts}}
<tr>
<td>{{@index}} </td>
<td>{{name}}</td>
</tr>
{{/each}}
【讨论】: