2015-12-11 33 views
0

一個簡單的問題,但我找不到簡單的解決方案。我必須爲此寫一個幫手嗎?Meteor,Blaze:每個創建一個簡單的循環?

我想在模板中創建特定數量的li項目。具體數字通過一個稱爲max的參數給出。

{{> rating max=10 value=rating }} 

<template name="rating"> 
    <ul class="rating"> 
     {{#each ?}} 
      <li class="star">\u2605</li> 
     {{/each }} 
    </ul> 
</template> 
+0

這是否回答你的問題? http://stackoverflow.com/questions/29307531/how-can-i-repeat-a-block-n-times-in-a-meteor-spacebars-template – Calvin

+0

不是。這是在onCreated中創建數組的明顯解決方案的複雜變體。我正在尋找像ng-repeat這樣的角色。 – dec

回答

2

http://docs.meteor.com/#/full/blaze_each

構造一個視圖呈現contentFunc在一個 序列中的每個項目。

因此,每個必須與一個序列(數組,光標)一起使用,所以你必須創建一個幫助器來創建一個使用#each的序列。 通常視圖是通過項目值來定製的,但在您的情況下,具有max大小的陣列可以完成這項工作。

或者您可以創建一個自定義模板助手,您可以在該助手中傳遞html來重複以及重複和concat html的數量。 喜歡的東西(代碼未測試):

// Register helper 
htmlRepeater = function (html,n) { 
    var out = ''; 
    for(var i=0 ; i<n;i++) 
     out.contat(html); 
    return Spacebars.SafeString(out); 
}; 

Template.registerHelper('repeat', htmlRepeater); 
------------------------ 
// in template.html 
{{{repeat '<li class="star">\u2605</li>' max}}} 
+0

但這聽起來很糟糕。創建一個數組來迭代特定的時間。有沒有更好的解決方案? – dec

+0

看到我的編輯答案。 – perusopersonale

+0

看起來是這樣。奇怪的是,這不是內置的。 – dec

0

只需從底層助手返回的項目所需的數目:

HTML:

{{> rating max=10 value=rating }} 

<template name="rating"> 
    <ul class="rating"> 
     {{#each myThings max}} 
      <li class="star">\u2605</li> 
     {{/each }} 
    </ul> 
</template> 

注意max需要通過傳遞html模板到{{#each}}

js:

Template.rating.helpers({ 
    myThings: function(max){ 
    // return an array 0...max-1 (as convenient as any other set of values for this example) 
    return Array.apply(null, Array(max)).map(function (x, i) { return i; }); 
    } 
}); 

當然,如果你遍歷集合,然後你可以只限制你.find()max

我還注意到您的rating模板沒有在任何地方使用參數value。您的意思是:

<ul class = "{{value}}"> 

或者是應該在其他地方替代的值?

0

我沒事用:

Template.registerHelper('repeat', function(max) { 
    return _.range(max); // undescore.js but every range impl would work 
}); 

{#each (repeat 10)}} 
    <span>{{this}}</span> 
{{/each}}