而是一个理论问题——如何在 Meteor 中渲染递归模板?例如,在评论中显示一个评论,评论子层数不限,这样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>
最佳答案
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
,然后打印该评论及其所有子评论等。
关于meteor - 如何在 Meteor 中做递归模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27299439/