I don't know how to deal with recursive array in template.and I can't find anything in handlebarsjs's docs
there are my codes: 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>
There are good ideas that deal with branch in template? Any help is appreciated.
You can use nested templates:
client side 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>
Also you don't really need has_branch
. Just check the length of the branch array instead as each will only loop if its an array and theres stuff in there
Akshat's answer is very good.
However, using it I had some problems with the event handling. The event was catched several times; once for every instances of the branch
template that contained the element throwing the event.
Not sure whether this is a bug or a feature...anyway I could overcome it using:
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");
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With