问题
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!
回答1:
You have some errors here.
First. you have a helper named getElements
and you are calling it like elements
Second you are calling the template into the same template {{> generate}}
<template name="generate">
{{#if elements}}
{{#each getElements}}
<div>{{#if elements}}{{> anotherTemplateName}}{{/if}}</div>
{{/each}}
{{else}}
{{> generate elements=getElements}}
{{/if}}
</template>
Also how the elements
helper looks? {{#if elements}}
A suggestion will be using nested templates here.
<template name="generate">
{{#if elements}}
{{> generateExample}}
{{else}}
{{> generate elements=getElements}}
{{/if}}
</template>
<!-- Generate Example Template -->
<template name="generateExample">
{{#each getElements}}
<div>{{#if elements}}{{> anotherTemplateName}}{{/if}}</div>
{{/each}}
</template>
Take a look into this Understanding Spacebars for a better learning experience
回答2:
Unlike Javascript, Spacebars considers an empty array [] to be falsy. So the initial {{#if elements}}
on leaf nodes (which have elements: []
) 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 include generate
:
<body>
{{> generate elements=getElements}}
</body>
<template name="generate">
{{#each elements}}
<div>{{#if elements}}{{> generate}}{{/if}}</div>
{{/each}}
</template>
来源:https://stackoverflow.com/questions/28689843/meteor-recursive-template-doesnt-work