2013-03-08 5 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 
      }] 

एचटीएमएल

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

एचटीएमएल

<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

अपने समय के लिए धन्यवाद। यह अच्छा विचार है! –

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

+0

का उपयोग कर इसे रोक सकते हैं, मुझे लगता है कि जब मैंने जवाब लिखा था तो काम नहीं किया था या नहीं ... @ ivan133 क्या आपने वास्तव में परीक्षण किया था? –

+0

हां, मैंने टिप्पणी पोस्ट करने से पहले आईडी का परीक्षण किया है। – ivan133

संबंधित मुद्दे