2011-01-04 4 views
12

私のようないくつかの反復と口ひげテンプレートレンダリングするコードがあります。ひげそりの反復でカウンタを設定する方法はありますか?

{{#items}} 
    some html code.... 
{{/items}} 

を私はそのように、反復にレンダリングされている項目の数を配置する:そこ

{{#items}} 
    This is the item [COUNTER-VAR] 
{{/items}} 

をこれを行うための何らかの方法です.. .. ??

+0

[口ひげでは、どのように現在のセクションのインデックスを取得する]の可能な重複(http://stackoverflow.com/questions/5021495/in-mustache-how-to-get-the-index-現在のセクションの) –

答えて

14

ハンドルバーが不要になりました。あなたは現在の口ひげに高次のセクションを使うことができます。これらは、基本的に、セクションの内容を引数として関数を呼び出すことができます。そのセクションが反復の中にある場合、そのセクションは反復の各アイテムに対して呼び出されます。

このテンプレート(便宜上&明確にするためのスクリプトタグ内に保持)

<script type="text/html" id="itemview"> 
    <table width="100%" border="0" cellspacing="0" cellpadding="3"> 
     <tbody> 
      {{#items}} 
       <tr> 
        <td>{{#count}}unused{{/count}}</td> 
        <td>{{.}}</td 
       </tr> 
      {{/items}} 
     </tbody> 
    </table> 
</script> 

...と、次のコードを考えると、あなたは、番号付きリストを作成することができます。

function buildPage(root) 
{ 
    var counter = 0; 
    var data = { 
     'items': [ 'England', 'Germany', 'France' ], 

     'count' : function() { 
      return function (text, render) { 
       // note that counter is in the enclosing scope 
       return counter++; 
      } 
     } 
    }; 

    // fetch the template from the above script tag 
    var template = document.getElementById('itemview').innerHTML; 
    document.getElementById("results").innerHTML = Mustache.to_html(template, data); 
} 

出力:反復内部 0イングランド 1ドイツ 2フランス

5

使用{{}} @Index。

{{#data}} 
    <p>Index is {{@index}}</p> 
{{/data}} 
関連する問題