[英]Handlebars.js access nested array values by variable
我有一個嵌套的對象,所有索引都是時間戳,它包含有關時間戳日期和當天事件的信息
data : {
1522620000: {
events: {
1522620940: {title: event1},
1522620970: {title: event2},
}
},
1522706400:
events: {
1522620940: {title: event4},
1522620970: {title: event6},
}
},
1523311200: {
events: {}
},
...
}
如何在不循環訪問數組的情況下訪問星期五的所有事件? 我只有時間戳1522706400
表示為可變timestamp
,我data[timestamp].events
一樣訪問它
目前我有
{{#each day}} //<-- another variable from a calendar.. don't care about it
{{# each data[timestamp].events }} //<-- the day contains information about the timestamp but does not contain the events..
{{ title }}
{{/each}}
{{/each}}
我通常使用AngularJS來完成類似的工作,但是我有一個客戶端希望我改用車把,對此我感到很困惑。
我自己就能解決。 我創建了以下Helper
Handlebars.registerHelper("getNestedValue", function(obj, options) {
var context,
response = "";
var timestamp = options.hash.key;
if(typeof obj[timestamp] !== 'undefined'){
var data = obj[timestamp]; // <-- all information for the timestamp
$.each(data.events, function (index, item) { // <-- loop through all events
context = item;
response += options.fn(context); // <-- include the variable to the template
});
}
return response;
});
所以我可以像訪問它
{{#getNestedValue ../data key=timestamp }}
<li class="icon-calendar-events-16">
<a href="{{ url }}">
{{ title }}
</a>
<small>{{ location }}</small>
</li>
{{/getNestedValue}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.