[英]How do I access an access array item by index in handlebars?
我正在嘗試在車把模板中指定數組中項目的索引:
{
people: [
{"name":"Yehuda Katz"},
{"name":"Luke"},
{"name":"Naomi"}
]
}
使用這個:
<ul id="luke_should_be_here">
{{people[1].name}}
</ul>
如果以上是不可能的,我將如何編寫一個可以訪問數組中特定項目的幫助程序?
嘗試這個:
<ul id="luke_should_be_here">
{{people.1.name}}
</ul>
以下內容,在 index 之前有一個額外的點,按預期工作。 此處,當索引后跟另一個屬性時,方括號是可選的:
{{people.[1].name}}
{{people.1.name}}
但是,在以下情況下需要方括號:
{{#with people.[1]}}
{{name}}
{{/with}}
在后者中,使用不帶方括號的索引號將得到一個:
Error: Parse error on line ...:
... {{#with people.1}}
-----------------------^
Expecting 'ID', got 'INTEGER'
順便說一句:括號(也)用於段文字語法,以引用否則無效的實際標識符(不是索引號)。 什么是有效標識符?
(在 YUI 中使用 Handlebars 進行測試。)
您現在可以為此使用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]
如果不編寫自己的助手,我看不到一個人在車把上走得太遠。
當您在each
數組中循環時,如果您想在當前項目的上下文中訪問另一個數組,您可以這樣做。
這是示例數據。
[ { name: 'foo', attr: [ 'boo', 'zoo' ] }, { name: 'bar', attr: [ 'far', 'zar' ] } ]
這是獲取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>
如果您想首先/最后獲取,請嘗試此操作。
{{#each list}}
{{#if @first}}
<div class="active">
{{else}}
<div>
{{/if}}
{{/each}}
{{#each list}}
{{#if @last}}
<div class="last-element">
{{else}}
<div>
{{/if}}
{{/each}}
如果數組未命名(僅將數組傳遞給模板),也可以使用以下語法:
<ul id="luke_should_be_here">
{{this.1.name}}
</ul>
在我的情況下,我想像這樣訪問自定義助手中的數組,
{{#ifCond arr.[@index] "foo" }}
哪個不起作用,但@julesbou 建議的答案起作用了。
工作代碼:
{{#ifCond (lookup arr @index) "" }}
希望這可以幫助! 干杯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.