我正在尝试在 Handlebars 模板中指定数组项的索引:
{
people: [
{"name":"Yehuda Katz"},
{"name":"Luke"},
{"name":"Naomi"}
]
}
使用这个:
<ul id="luke_should_be_here">
{{people[1].name}}
</ul>
如果上述方法不可行,我该如何编写一个 helper 来访问数组中的特定项?我正在尝试在 Handlebars 模板中指定数组项的索引:
{
people: [
{"name":"Yehuda Katz"},
{"name":"Luke"},
{"name":"Naomi"}
]
}
使用这个:
<ul id="luke_should_be_here">
{{people[1].name}}
</ul>
如果上述方法不可行,我该如何编写一个 helper 来访问数组中的特定项?试试这个:
<ul id="luke_should_be_here">
{{people.1.name}}
</ul>
{{people.[1].name}}
{{people.1.name}}
然而,在以下情况下方括号是必需的:
{{#with people.[1]}}
{{name}}
{{/with}}
Error: Parse error on line ...:
... {{#with people.1}}
-----------------------^
Expecting 'ID', got 'INTEGER'
get
助手来完成此操作:(get people index)
虽然如果你收到一个关于需要索引为字符串的错误,请执行以下操作:
(get people (concat index ""))
{{#each array}}
{{@index}}
{{/each}}
如果您不熟悉未记录的功能,同样可以在此处完成:
Handlebars.registerHelper('index_of', function(context,ndx) {
return context[ndx];
});
然后在模板中
{{#index_of this 1}}{{/index_of}}
在我获取到……之前,我已经写了上面的内容。
this.[0]
如果没有编写自己的helpers,我认为使用handlebars无法取得太大进展。
以下方式是错误的:
{{#each obj[key]}}
...
{{/each}}
你需要做:
{{#each (lookup obj key)}}
...
{{/each}}
{{lookup ../../btnPercentages @../index}}
。 - MegaTux如果您想获取第一/最后一个,请尝试这个。
{{#each list}}
{{#if @first}}
<div class="active">
{{else}}
<div>
{{/if}}
{{/each}}
{{#each list}}
{{#if @last}}
<div class="last-element">
{{else}}
<div>
{{/if}}
{{/each}}
当你使用each
循环遍历数组并且想要在当前项的上下文中访问另一个数组时,可以像这样操作。
以下是示例数据。
[ { name: 'foo', attr: [ 'boo', 'zoo' ] }, { name: 'bar', attr: [ 'far', 'zar' ] } ]
以下是handlebars代码,用于获取attr
数组中的第一项。
{{#each player}} <p> {{this.name}} </p>
{{#with this.attr}} <p> {{this.[0]}} </p> {{/with}}
{{/each}}
它将输出
<p> foo </p> <p> boo </p>
<p> bar </p> <p> far </p>
this
可以代替this.[0]
。 - Fatih Acet <ul id="luke_should_be_here">
{{this.1.name}}
</ul>
{{#ifCond arr.[@index] "foo" }}
之前的方法没有奏效,但是@julesbou提供的答案有效。
有效代码:
{{#ifCond (lookup arr @index) "" }}
{{ websites.[0] }}
的东西。 - Mattpeople.content.1.name
的事情。 - aceofspades