2016-03-08 55 views
1

我正在使用「循環」模板來顯示元素及其子元素。所以如果結構是三層深的,loopIt-template會被使用三次。流星:獲取循環模板的級別信息

<template name="main"> 
    {{ < loopIt }} 
</template> 

<template name="loopIt"> 
    {{#each elements}} 
     {{title}} {{level}} 
     {{ > loopIt }} 
    {{/each}} 
</template> 

是否可以獲取元素所在的級別信息並將其輸出爲{{level}}

結果應該是這樣的:

first element 1 
    first subelement 2 
    second subelement 2 
     first subsubelement 3 
    third subelement 2 
second element 1 
+0

難道你沒有關於你的數據模型的關卡嗎?用Blaze或「自定義骯髒技巧」處理數據比從數據更容易處理 –

+0

我對父引用使用模型樹結構。所以我沒有關卡信息。只需引用每個元素的下一個父元素:-( – user3848987

+0

您是否生成樹?如果是,我會在構建時在每個節點上添加級別信息。 –

回答

1

你可以試試這個?

首先,定義一個幫手,你走在遞歸更深

Template.loopIt.helpers({ 
    add: function(level) { 
    return level + 1; 
    } 
}); 

然後在模板傳遞當前的水平和所定義的輔助增加它作爲你的一個新的水平去增加水平遞歸。

<template name="main"> 
    {{ < loopIt level = 0}} 
</template> 

<template name="loopIt"> 
    {{#each elements}} 
     {{title}} {{../level}} 
     {{ > loopIt level = (add ../level)}} 
    {{/each}} 
</template> 

請注意,在each循環中,您會丟失父上下文。爲了再次訪問父上下文,有必要在變量level前加上../