I tried to have a recursive template like this:
<template name="generate">
{{#if elements}}
{{#each elements}}
<div>{{#if elements}}{{> generate}}{{/if}}</div>
{{/each}}
{{else}}
{{> generate elements=getElements}}
{{/if}}
</template>
with the helper:
Template.generate.helpers({
getElements: function() {
return Elements.find()
}
})
and the "Elements" data object:
[{
_id : "fgQ4GHrrZGFFGWPZQ",
elements" : [{
_id : "hY8iAYJC4KBwGKN84",
elements : []
}]
},{
_id : "rtMNfaQYwqzNTYqoD",
elements : [{
_id : "p2wJeGdtiGMYBQtpW",
elements : []
}]
}]
I'm running into an issue where the keyboard events become unresponsive and other functionality ceases to work. Were templates not designed to handle this kind of recursion? If so, I'll try a different approach but I figured this would work though. Anyone else seeing this or have any suggestions? Thanks!
Edit: This will work. My problem was setting up a keyboard event handler on the "rendered" callback which was being called more than once (each time the template was rendered) which caused the issue I mentioned. I would delete this question but stackoverflow. Thanks everybuddy!
Unlike Javascript, Spacebars considers an empty array
[]
to be falsy. So the initial{{#if elements}}
on leaf nodes (which haveelements: []
) will be false, triggering the{{> generate elements=getElements}}
which ultimately causes an infinite recursion.You could fix this by removing the
{{#if}}
altogether, and then calling{{> generate elements=getElements}}
when you initially includegenerate
:You have some errors here.
First. you have a helper named
getElements
and you are calling it likeelements
Second you are calling the template into the same template
{{> generate}}
Also how the
elements
helper looks?{{#if elements}}
A suggestion will be using nested templates here.
Take a look into this Understanding Spacebars for a better learning experience