当前位置: 动力学知识库 > 问答 > 编程问答 >

tree - How to do recursive templates in Meteor?

问题描述:

rather a theoretical question - how can I render recursive templates in Meteor? For example, displaying a comment on comment with unlimited number of comment sub-levels so that HTML would be diplayed as the following?

<section>

some text

<section>

nested text

<section>

further nested text and sections

.....

</section>

</section>

</section>

In my case I pass to the "tree" template a mongoDB document and this document can have unlimited number of sub-content levels. My example below doesn't work the way I want.

<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>

网友答案:

A simplified example of recirsuve, say you had a post sample template of:

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

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

and a post helper of:

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

I would create a template for the comment layout and provide a helper in that for sub-comments, depending on your data structure something like the following:

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

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

</template>

and then the helper along the lines of:

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

This would recursively produce the comments template for each sub-comment then roll back up the tree to the next #each and then print that comment and all of its sub-comments etc.

分享给朋友:
您可能感兴趣的文章:
随机阅读: