【问题标题】:How to use recursive template?如何使用递归模板?
【发布时间】:2013-02-23 19:13:45
【问题描述】:

我不知道如何处理模板中的递归数组。我在 handlebarsjs 的文档中找不到任何内容

有我的代码: js:

var 分支 = [{ name:"firstLayerNodeA", has_branch:真, 分支:[{ 名称:“第二个布局节点A”, has_branch:false },{ 名称:“第二个布局节点B”, has_branch:真, 分支:[{ 名称:“第三层节点A”, has_branch:真, 分支:[{ //第四层 //第五层 //..... }] }] }] },{ name:"firstLayerNodeB", has_branch:false }]

html

<Template name="tree">
  <ul>
  {{#each brach}}
      <li>
        name
        {{#if has_branch}}
          <ul>
          {{#each brach}}
              <li>
                name
                {{#if has_brach}}
                      {{#each brach}}
                          .....third layer
                          .....fourth layer
                          ....
                      {{/each}}
                {{/if}}
              </li>
          {{/each}
          </ul>
        {{/if}}
      </li>
  {{/each}}
  </ul>
</Template>

有处理模板分支的好主意吗? 任何帮助表示赞赏。

【问题讨论】:

    标签: meteor


    【解决方案1】:

    Akshat's answer 很好。 但是,使用它时,我在事件处理方面遇到了一些问题。该事件被多次捕获;对于包含引发事件的元素的 branch 模板的每个实例一次。

    不确定这是错误还是功能...无论如何我可以使用以下方法克服它:

    Template.branch.events({
      'click': function (e,b) {    
        console.log("this will show up as often as deep your tree is");
        if (this._id==b.data._id)
          console.log("this will show up only once");
      }
    });
    

    【讨论】:

    • 您可以使用 e.stopPropagation() 来防止这种情况
    • 当我写下答案时,我认为这不起作用或不像预期的那样......@ivan133 你现在真的测试了吗?
    【解决方案2】:

    您可以使用嵌套模板:

    客户端 js

    Template.tree.branch = function() {
        var branch = ...
        return branch;
    }
    

    HTML

    <template name="tree">
      <ul>
        {{#each branch}}
          <li>    
            {{>branch}}
          </li>       
        {{/each}}
      </ul>
    </template>
    
    <template name="branch">
        {{name}}
        {{#if branch.length}}
           <ul>
               {{#each branch}}
                   <li>
                       {{>branch}}
                   </li>
               {{/each}}
           </ul>
        {{/if}}
    </template>
    

    你也不需要has_branch。只需检查分支数组的长度,因为每个只有在它是一个数组并且里面有东西时才会循环

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-03
      • 1970-01-01
      • 2011-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-07
      相关资源
      最近更新 更多