2014-12-04 70 views
3

相當理論上的問題 - 我如何渲染流星中的遞歸模板?例如,顯示評論的評論,其中包含無限數量的評論子級別,以便將HTML顯示爲以下內容?如何在流星中做遞歸模板?

<section> 
    some text 
    <section> 
     nested text 
     <section> 
     further nested text and sections 
     ..... 
     </section> 
    </section> 
</section> 

在我來說,我通過「樹」模板MongoDB的文件,這個文件可以有子含量水平的數量不受限制。我的下面的例子不按我想要的方式工作。

<template name="tree"> 
    <div class="wrapper" style="border:1px solid red"> 
     <ul> 
      {{#each getStructure}} 
      <li> 
       {{#each content}} 
       <ul> 

        <li> 
         <a class="item">{{text}}</a> 

         <!-- TODO: this stuff needs to be recursive. 
         {{#if sub_content}} 
         <ul> 
          {{#each sub_content}} 
           <li> 
           <a class="item">{{text}}</a> 
           {{#if sub_content}} 
           .... 
           {{/if}} 
           </li> 
          {{/each}} 
         </ul> 
         {{/if}} 
        </li> 

       </ul> 
       {{/each}} 
      </li> 

      {{/each}} 
     </ul> 
    </div> 
</template> 

回答

4

recirsuve的一個簡單的例子,假設你有一個職位樣本模板:

<template name="post"> 
    {{post_text}} 

    {{#each comments}} 
    {{>comment}} 
    {{/each}} 
</template> 

和後幫手:

Template.post.helpers({ 
    comments: function() { 
    return CommentCollection.find({post_id: this._id, parent_id: {$exists: 0}}); 
    } 
}); 

我想創建一個模板的註釋佈局,並提供一個幫助,其中的子註釋取決於您的數據結構,如下所示:

<template name="comment"> 
    {{comment_text}} 

    {{#each sub_comment}} 
    {{> comment}} 
    {{/each}} 

</template> 

,然後沿的線條助手:

Template.comment.helpers({ 
    sub_comments: function() { 
    return CommentCollection.find({parent_id: this._id}); 
    } 
}); 

這將遞歸地爲每個子評論評論模板然後回滾上樹下一#each然後打印該評論和所有的其子評論等

+0

謝謝亞倫。你的回覆是現貨,但是我發現我的問題不是模板本身,而是應用程序崩潰在複雜的數據上。你似乎是Meteor和Hanlebars的知識分子 - 你能否看看我的另一個問題? http://stackoverflow.com/questions/27364206/meteor-throws-exception-exception-from-tracker-recompute-function-too-much-rec – lekso 2014-12-08 18:16:00

+0

這個演示非常有幫助。 – ergusto 2015-08-21 16:00:08