2013-07-18 28 views
11

如何使用變量而不是硬編碼值訪問句柄模板中的數組元素? 我需要做的是這樣的:在目前帶動態索引的手把陣列訪問

{{#each condition in conditions}} 
    {{App.ops.[condition.op].name}} 
{{/each}} 

不給我解析錯誤,但在運行時不返回我什麼。 如果我做這樣的事情:

{{App.ops.[1].name}} 

它的工作原理,但它不是我要找的

+0

你有沒有找到任何解決方法?我被困在同一個問題上。 – Mathieu

回答

9

相關的my answer on another question


您可以使用the built-in lookup helper

lookup helper al低位使用Handlebars變量進行動態參數解析。這對於解析數組索引的值很有用。

使用lookup,您的例子可以寫成

{{#each condition in conditions}} 
    {{#with (lookup ../App.ops condition.op)}} 
     {{name}} 
    {{/with}} 
{{/each}} 

(注意,如果沒有你的數據結構的知識,我在調查的App.ops位置的假設。)

+0

這應該是被接受的答案 – Jivan

0

您需要爲您的問題幫手。以下是使用索引值解決問題的示例解決方案。如果你想使用一些條件,你也可以這樣做。

Handlebars.registerHelper("each_with_index", function(array, options) { 
    if(array != undefined && array != null && array.length > 0){ 
     var html = new StringBuffer(); 
     for (var i = 0, j = array.length; i < j; i++) { 
      var item = array[i]; 
      item.index = i+1; 

      // show the inside of the block 
      html.append(options.fn(item)); 
    } 

    // return the finished buffer 
    return html.toString(); 
} 
return ""; 
}); 

然後,你可以做這樣的事情

{{#each_with_index condition in conditions}} 
    {{App.ops.[condition.index].name}} 
{{/each_with_index}} 
3

你可以寫一個簡單的輔助剛剛從陣列中獲取價值

Handlebars.registerHelper('getmyvalue', function(outer, inner) { 
    return outer[inner.label]; 
}); 

,然後用它在模板像

{{#each outer}} 
    {{#each ../inner}} 
     {{getmyvalue ../this this }} 
{{/each}} 

../this個參考當前外項目,this - 當前內項目數據來模板

例子:

{ 
    outer: { 
     1: { foo: "foo value" }, 
     2: { bar: "bar value" } 
    }, 
    inner: { 
     1: { label: "foo" }, 
     2: { label: "bar" } 
    } 
}