2013-03-08 54 views
8

我不知道該如何處理遞歸陣列template.and我找不到handlebarsjs的文檔什麼如何使用遞歸模板?

有我的代碼: JS:

 

    var branch = [{ 
       name:"firstLayerNodeA", 
       has_branch:true, 
       branch:[{ 
         name:"secondLayoutNodeA", 
         has_branch:false 
        },{ 
         name:"secondLayoutNodeB", 
         has_branch:true, 
         branch:[{ 
           name:"thirdLayerNodeA", 
           has_branch:true, 
           branch:[{ 
             //fourth Layer 
             //fifth Layer 
             //..... 
           }] 
         }] 
       }] 
      },{ 
       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> 

有好的想法,處理模板分支? 任何幫助表示讚賞。

回答

4

您可以使用嵌套的模板:

客戶端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。只是檢查分支數組的長度,而不是每個只會循環,如果它的一個數組,那裏有東西在裏面

+0

感謝您的時間。這是個好主意! – 2013-03-10 07:23:29

2

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"); 
    } 
}); 
+1

您可以通過使用e.stopPropagation() – ivan133 2015-05-11 16:44:30

+0

我想,回料,當我寫的答案沒有工作或沒有阻止這個... @ ivan133你實際測試,如果現在呢? – 2015-05-12 07:27:32

+0

是的,我已經張貼評論前測試ID。 – ivan133 2015-05-13 08:22:51