2014-02-14 47 views
2

如何將數組值加載到流星中的模板變量?請看下面的代碼,並建議我該怎麼做?如何將數組值加載到流星JS中的模板變量?

HTML代碼:

<template name="header"> 
<div class="header"> 
    {{#each alphabets}} 
     <div class="alphabets">{{this}}</div> 
    {{/each}} 
</div> 
</template> 

JS代碼:

//the below array values are load dynamically above template 
var Alphas = ['ALL', 
       'A', 'B', 'C', 'D','E', 'F', 
       'G', 'H', 'I', 'J','K', 'L', 
       'M', 'N', 'O', 'P','Q', 'R', 
       'S', 'T', 'U', 'V','W', 'X', 
       'Y', 'Z' 
       ] 

     Template.header.alphabets = function (i) 
     { 
      return Alphas[i]; 
     }; 

回答

10

HTML模板:

<template name="header"> 
    <div class="header"> 
    {{#each alphabets}} 
     <div class="alphabets">{{this}}</div> 
    {{/each}} 
    </div> 
</template> 

模板JS:

var Alphas = ['ALL', 
       'A', 'B', 'C', 'D','E', 'F', 
       'G', 'H', 'I', 'J','K', 'L', 
       'M', 'N', 'O', 'P','Q', 'R', 
       'S', 'T', 'U', 'V','W', 'X', 
       'Y', 'Z']; 

Template.header.alphabets = function() { 
    return Alphas; 
}; 

我測試了這一點,它的工作原理。

基本上,你可以像遊標一樣傳遞數組,每一個都會迭代它們。

如果您的數組中有鍵/值對,那麼您可以像處理mongo文檔一樣解決它們。

1

助手通常返回整個陣列,而不是單個的索引元素。循環由{{#each}}塊完成。所以,你的助手不應該有參數,看上去簡直像:

Template.header.alphabets = function() { 
    return Alphas; 
}; 

你直接調用它,沒有提到Alphas(因爲你的模板不知道變量)。

{{#each alphabets}} 
    <div class="alphabets">{{this}}</div> 
{{/each}} 

 


當你想想這樣這是很自然的:爲alphabets#each元素,打印含有divthis元素。

0

而是遍歷一個數組,你可以使用所有的數組值如下

<template name="alphabet-template"> 
    {{#if alphabets}} 
    <div class="post-alphabet"> 
     <p> Element: {{alphabets}}</p> 
    </div> 
    {{/if}} 
</template> 
1
Template.header.alphabets 

depricated。

使用Template.templateName.helpers保證。

<template name="newTextLabel"> 
    {{#each textType}} 
    <span class="label label-primary pull-right">{{this}}</span> 
    {{/each}} 
</template> 

Template.newTextLabel.helpers ({ 
    textType: function() { 
    var xxx = ZZZ.findOne(this); 
    return xxx.tag; 
} 
}) 

收集ZZZ有一個名爲 '標籤' 陣列

文件