2016-08-07 5 views
0

次の表を作成しようとしています。ネストされたハンドルバーのループでインデックスを使用する

enter image description here

私はハンドルバー(PS。私はこのオブジェクトを再構築できます。べき私は?)にoに合格しています。

var o={ 
years:[1800,1900,2012], 
countries:["Africa","America","Asia","Europe","Oceania"], 
data:[ 
    [107,133,1052], 
    [null,156,954], 
    [635,null,4250], 
    [203,408,740], 
    [2,6,38] 
    ] 
}; 

http://handlebarsjs.com/builtin_helpers.htmlによると、私は{{@index}}を経由して、インデックスにアクセスすることができます。しかし、私は2つのループを持っているので、どのように私はそれらの両方にアクセスして正しいデータを得ることができますか?

<table> 
    <thead> 
     <tr> 
      <th></th> 
      {{#each years}} {{!-- is "#each years" and "#years" the same thing??? --}} 
      <th>{{this}}</th> 
      {{/each}} 
     </tr> 
    </thead> 
    <tbody> 
     {{#each countries}} 
     <tr> 
     <td>{{this}}</td> 
     {{#each data}} 
     <tr> 
      <td>{{this}}????</td> 
     </tr> 
     {{/each}} 
     </tr> 
     {{/each}} 
    </tbody> 
</table> 

答えて

0

まず、{{#each years}}{{#years}}と同じ結果になります。後者の形式はMustacheであり、ライブラリはSectionと呼ばれています。 Handlebarsのドキュメントではdifferences between Handlebars block expressions and Mustache Sectionsについて説明しています。

あなたの{{#each countries}}ループ内から{{#each data}}を使用できない理由は、国のループ内のデータコンテキストが現在の国の反復であるためです。 dataオブジェクトにアクセスするには、親スコープまで到達する必要があります。これはHandlebars pathsで行われ、{{../data}}と書かれます。

しかし、このシナリオでは、現在の国の反復のインデックスと一致するインデックスdataの特定の要素を取得したいと考えています。このため、lookup helperを使用できます。結果は次のようになります。

<table> 
    <thead> 
     <tr> 
      <th></th> 
      {{#each years}} 
       <th>{{this}}</th> 
      {{/each}} 
     </tr> 
    </thead> 
    <tbody> 
     {{#each countries}} 
      <tr> 
       <td>{{this}}</td> 
       {{#each (lookup ../data @index)}} 
        <tr> 
         <td>{{this}}</td> 
        </tr> 
       {{/each}} 
      </tr> 
     {{/each}} 
    </tbody> 
</table> 
関連する問題