meteor - 如何在 Meteor 中做递归模板?

标签 meteor tree mustache

而是一个理论问题——如何在 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/

相关文章:

javascript - 模板内的 Handlebars 模板

javascript - 错误: ETIMEDOUT on NPM usage in Meteor

javascript - 我正在寻找检查树是否对称的迭代解决方案

sql-server-2005 - 多父树(或有向图)实现sql server 2005

javascript - 使用 Mustache 循环 json

javascript - MongoDB/JS : find the minimum (earliest) date

mongodb - 将多边形插入 MongoDB 写入空值而不是坐标(在 Meteor 1.1.0.2 上)

meteor - 在 Meteor 包中使用 npm

c++ - 二叉搜索树计算节点的坐标