2014-02-14 44 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有一个名为 '标签' 阵列

文件