handlebars内でのデータアクセスについて
- handlebars内で、jsonデータ階層を遡ってアクセスしたい
response: {
url: "http://www.hogehogeweiwei.com?weiwei=1&ponpon=2",
datas: [
0: {
id: 0,
title: "あああああ",
hoges:[
0:{hoge_id:0, comment: "hogehoge"},
1:{hoge_id:1, comment: "hogehoge"},
2:{hoge_id:2, comment: "hogehoge"},
]
},
1: {
id: 1,
title: "いいいいい",
hoges:[
0:{hoge_id:0, comment: "hogehoge"},
1:{hoge_id:1, comment: "hogehoge"},
2:{hoge_id:2, comment: "hogehoge"},
]
},
2: {
id: 2,
title: "ううううう",
hoges:[
0:{hoge_id:0, comment: "hogehoge"},
1:{hoge_id:1, comment: "hogehoge"},
2:{hoge_id:2, comment: "hogehoge"},
]
}
]
このデータを下記テンプレートに突っ込む
{{#each response.datas}}
<li data-item-id="{{id}}">
<div>{{title}}</div>
{{#each hoges}}
<a href="{{../../url}}"> <!-- hogesまでネストしたところで2階層上のデータにアクセスしたい -->
<li data-hoge-id="{{hoge_id}}">
<div>{{comment}}</div>
</li>
</a>
{{/each}}
</li>
{{/each}}
これだとダメ。
hogesをカレントにして2階層上に上がれない。
handlebarsの"../"はカレントデータの一階層上に行くわけではないらしい。
http://handlebarsjs.com/
The ../ path segment references the parent template scope, not one level up in the context. This is because block helpers can invoke a block with any context, so the notion of "one level up" isn't particularly meaningful except as a reference to the parent template scope.
上記テンプレートでresponse.urlにアクセスできなかったのは、responseでコンテキストが固定されてないから?
hogesからみて、
- 1個上の階層:datas(eachでコンテキスト固定されてるから)
- 2個上の階層:?(コンテキスト固定されてない)
なので、こうしてやる必要がある
{{#with response}} <!-- ここでコンテキスト固定する -->
{{#each datas}}
<li data-item-id="{{id}}">
<div>{{title}}</div>
{{#each hoges}}
<a href="{{../../url}}">
<li data-hoge-id="{{hoge_id}}">
<div>{{comment}}</div>
</li>
</a>
{{/each}}
</li>
{{/each}}
{{/with}}
これでいけました。